This is outdated documentation for Sycamore.
For up-to-date documentation, see the latest version (v0.8).
template!
Sycamore uses the template!
macro as an ergonomic way to create complex user interfaces. You might
have already seen it in the “Hello, World!” example.
Syntax
Elements
Creating HTML elements is easy as pie with the template!
macro. Since you’ll likely want to create
a lot of elements in your app, there is a special terse syntax.
template!
Text nodes
Of course, in your app, you probably want to display some text. To create a text node, simply add a
string literal (using "
).
template!
Nesting
Creating all these top-level nodes is not very useful. You can create nested nodes like so.
template!
Attributes
Attributes (including classes and ids) can also be specified.
template!
dangerously_set_inner_html
The special dangerously_set_inner_html
attribute is used to set an HTML string as the child of an
element. This should generally be avoided because it is a possible security risk. Never pass user
input to this attribute as that will create an XSS (Cross-Site Scripting) vulnerability.
template!
Instead, when displaying user input, use interpolation syntax instead.
Events
Events are attached using the on:*
directive.
template!
Fragments
As seen in previous examples, templates can also be fragments. You can create as many nodes as you want at the top-level.
template!
Fragments can also be empty.
template!
Interpolation
Templates can contain interpolated values. Anything that implements std::fmt::Display
will
automatically be inserted as text into the DOM tree. For example:
let my_number = 123;
template!
Other templates created using the template!
macro can also be interpolated using the same syntax.
For example:
let inner_template = template! ;
let outer_template = template! ;
The cool thing about interpolation in Sycamore is that it is automatically kept up to date with the value of the expression. Learn more about this in Reactivity.