sailfish/docs/en/docs/syntax/tags.md

108 lines
2.1 KiB
Markdown
Raw Normal View History

2020-06-19 01:53:16 -04:00
# Tags
## Code block
You can write Rust statement inside `<% %>` tag.
=== "Template"
``` rhtml
<%
let mut total = 0;
for i in 1.. {
total += i;
if i > 100 {
break;
}
}
%>
<div>total = <%\html total %></div>
```
=== "Result"
``` html
<div>total = 105</div>
```
2020-06-19 01:53:16 -04:00
!!! Note
2024-03-11 17:33:11 -04:00
Make sure that you cannot omit braces, parenthesis, and semicolons.
2020-06-19 01:53:16 -04:00
Sailfish is smart enough to figure out where the code block ends, so you can even include `%>` inside Rust comments or string literals.
=== "Template"
``` text
<% /* Tag does not ends at %>! */ %>
```
=== "Result"
``` text
```
2020-06-19 01:53:16 -04:00
If you need to simply render `<%` character, you can escape it, or use evaluation block (described below).
=== "Template"
``` text
<%% is converted into <%- "<%" %> character.
```
=== "Result"
``` text
<% is converted into <% character
```
2020-06-19 01:53:16 -04:00
Although almost all Rust statement is supported, the following statements inside templates may cause a strange compilation error.
2024-03-11 17:33:11 -04:00
- Function/Macro definition that render some contents
- `impl` item
- Macro call which defines some local variable.
- Macro call which behaviour depends on the path to source file
- Generator expression (yield)
2020-06-19 01:53:16 -04:00
## Evaluation block
Rust expression inside `<%\mode %>` tag is evaluated and the result will be rendered.
2020-06-19 01:53:16 -04:00
=== "Template"
``` rhtml
<% let a = 1; %><%\html a + 2 %>
```
=== "Result"
``` text
3
```
2020-06-19 01:53:16 -04:00
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.
2020-06-19 01:53:16 -04:00
=== "Template"
2020-06-19 01:53:16 -04:00
``` rhtml
<div>
<%- "<h1>Hello, World!</h1>" %>
</div>
```
2020-06-19 01:53:16 -04:00
=== "Result"
``` html
<div>
<h1>Hello, World!</h1>
</div>
```
2020-06-19 01:53:16 -04:00
!!! Note
2024-03-11 17:33:11 -04:00
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.
2020-06-19 01:53:16 -04:00
``` rhtml
<% let result = %><%\html 1 %><% ; %>
2020-06-19 01:53:16 -04:00
```