Literals and Expressions
Literals
If expressions resolve to types that implement Display, they will be converted to strings and inserted into the DOM as a Text node.
note
String literals create Text nodes, which are treated as strings by the browser. Hence, even if the expression contains a <script> tag you can’t fall for XSS and such security issues, unless of course you wrap the expression in a <script> block.
All display text must be enclosed by {} blocks because the text is handled as an expression. This is the largest deviation from normal HTML syntax that Yew makes.
1. use yew::prelude::*;
3. let text = "lorem ipsum";
4. html!{
5. <>
6. <div>{text}</div>
7. <div>{"dolor sit"}</div>
8. <span>{42}</span>
9. </>
10. };
Expressions
You can insert expressions in your HTML using {} blocks, as long as they resolve to Html
1. use yew::prelude::*;
3. let show_link = true;
5. html! {
6. <div>
7. {
8. if show_link {
9. html! {
10. <a href="https://example.com">{"Link"}</a>
11. }
12. } else {
13. html! {}
14. }
15. }
16. </div>
17. };
It often makes sense to extract these expressions into functions or closures to optimize for readability:
1. use yew::prelude::*;
3. let show_link = true;
4. let maybe_display_link = move || -> Html {
5. if show_link {
6. html! {
7. <a href="https://example.com">{"Link"}</a>
8. }
9. } else {
10. html! {}
11. }
12. };
14. html! {
15. <div>{maybe_display_link()}</div>
16. };
