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.

Literals and Expressions - 图1note

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 text is handled as an expression. This is the largest deviation from normal HTML syntax that Yew makes.

  1. use yew::prelude::*;
  2. let text = "lorem ipsum";
  3. html!{
  4. <>
  5. <div>{text}</div>
  6. <div>{"dolor sit"}</div>
  7. <span>{42}</span>
  8. </>
  9. };

Expressions

You can insert expressions in your HTML using {} blocks, as long as they resolve to Html

  1. use yew::prelude::*;
  2. let show_link = true;
  3. html! {
  4. <div>
  5. {
  6. if show_link {
  7. html! {
  8. <a href="https://example.com">{"Link"}</a>
  9. }
  10. } else {
  11. html! {}
  12. }
  13. }
  14. </div>
  15. };

It often makes sense to extract these expressions into functions or closures to optimize for readability:

  1. use yew::prelude::*;
  2. let show_link = true;
  3. let maybe_display_link = move || -> Html {
  4. if show_link {
  5. html! {
  6. <a href="https://example.com">{"Link"}</a>
  7. }
  8. } else {
  9. html! {}
  10. }
  11. };
  12. html! {
  13. <div>{maybe_display_link()}</div>
  14. };