yew-template
This crate allows you to separate your HTML from your Rust code when using Yew.
Getting Started
Hello World
Hello [name]!
let html = template_html!;
The code above will actually compile to the following code:
let html = html! ;
Usage
Attributes
Hello [name]!
let html = template_html!;
Variables
let name = "World";
let html = template_html!;
Would compile to:
let name = "World";
let html = html! ;
When the name of your variable isn't the same as the name in the template, you can use the following syntax:
let last_name = "World";
let html = template_html!;
Expressions
let name_reversed = Stringfrom;
let html = template_html!;
Which will also display Hello World! as the output is as follows:
let name_reversed = Stringfrom;
let html = html! ;
Note that the brackets around expressions are required for expressions.
Example with Yew callbacks
Hello [name]!
let link = ctx.link;
let html = template_html!;
Optional variables
Optional variables are marked with an opt_ prefix or an _opt suffix, at your option.
Their value is expected to be an Option<T>.
Optional variables work with optional html elements. Mark an element with the opt attribute to make it optional. An optional element will only be rendered if ALL the optional variables it contains are Some. Note that variables contained by smaller optional elements are excluded from this requirement.
Hello [name]!
Age
You are [opt_age] years old!
In the example above, the div block will not be shown if opt_age is None.
Let's see how optional elements can be nested.
Hello [name]!
Age
You are [opt_age] years old!
And you are born in [opt_birth_city].
Here, both opt_age and opt_birth_city are optional. opt_age would be displayed even if opt_birth_city is None. However, if opt_age is None, opt_birth_city will not be displayed regardless of its value.
From the Rust side, there is no usage difference. Note that brackets are required (for now).
let opt_age: = Some;
let opt_birth_city: = None;
let html = template_html!;
Iterators
Iterators work similarly to optional variables. The iterator variables are marked with an iter_ prefix or an _iter suffix, at your option.
The looping html element is marked with the iter attribute. The element will reproduce until one of the iterators it depends on is empty.
Contributors:
[contributors_iter] ([commits_iter] commits)
let contributors = vec!; // Owned values need to be declared as `let` or they would be freed before the template is rendered.
let html = template_html!;
The code above will act as the following:
let contributors = vec!;
let html = html! ;
Notes
-
Litteral values are NOT escaped because they come from your code. Using a litteral value of
value closed by quotes" trailing stuffwill cause problems. This will be fixed in a future version. -
You can use multiple top-level elements in your html template file.
License: MIT