Tags
Code block
You can write Rust statement inside <% %> tag.
<%
let mut total = 0;
for i in 1.. {
total += i;
if i > 100 {
break;
}
}
%>
<div>total = <%= total %></div>
<div>total = 5151</div>
Note
Make sure that you cannot omit braces, parenthesis, and semicolons.
Sailfish is smart enough to figure out where the code block ends, so you can even include %> inside Rust comments or string literals.
<% /* Tag does not ends at %>! */ %>
If you need to simply render <% character, you can escape it, or use evaluation block (described below).
<%% is converted into <%- "<%" %> character.
<% is converted into <% character.
Although almost all Rust statement is supported, the following statements inside templates may cause a strange compilation error.
- Function/Macro definition that render some contents
implitem- Macro call which defines some local variable.
- Macro call which behaviour depends on the path to source file
- Generator expression (yield)
Evaluation block
Rust expression inside <%= %> tag is evaluated and the result will be rendered.
<% let a = 1; %><%= a + 2 %>
3
If the result contains &"'<> characters, sailfish replaces these characters with the equivalent html.
If you want to render the results without escaping, you can use <%- %> tag or configure sailfish to not escape by default.
<div>
<%- "<h1>Hello, World!</h1>" %>
</div>
<div>
<h1>Hello, World!</h1>
</div>
Note
Evaluation block does not return any value, so you cannot use the block to pass the render result to another code block. The following code is invalid.
<% let result = %><%= 1 %><% ; %>
Component block
Rust expression inside <%+ %> tag is evaluated and then rendered by
calling its render_once_to() method with the current output buffer. When a
filter is applied to the component, Sailfish calls render_once() first and
passes the rendered string to the filter. If the value does not have the
appropriate method in scope, a compile-time error will be reported.
Both TemplateSimple and TemplateOnce can be used for components. Import the
corresponding trait so its rendering methods are available. The example below
uses TemplateSimple for both templates, so val is accessed directly. With
TemplateOnce, use self.val instead.
<strong>A <%= val %></strong>
B <%+ A { val: "example" } %>
B <strong>A example</strong>