Skip to content

Latest commit

 

History

History
71 lines (57 loc) · 1.53 KB

literals-and-expressions.mdx

File metadata and controls

71 lines (57 loc) · 1.53 KB
title
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.

use yew::prelude::*;

let text = "lorem ipsum";
html!{
    <>
        <div>{text}</div>
        <div>{"dolor sit"}</div>
        <span>{42}</span>
    </>
};

Expressions

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

use yew::prelude::*;

let show_link = true;

html! {
  <div>
    {
      if show_link {
        html! {
          <a href="https://example.com">{"Link"}</a>
        }
      } else {
        html! {}
      }
    }
  </div>
};

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

use yew::prelude::*;

let show_link = true;
let maybe_display_link = move || -> Html {
  if show_link {
    html! {
      <a href="https://example.com">{"Link"}</a>
    }
  } else {
    html! {}
  }
};

html! {
     <div>{maybe_display_link()}</div>
};