View

There are 2 major way to write views in sauron. The first one is using the node! macro which allows you to write an html like syntax. The second one is using function call. They have no difference in performance.

Listing 1: Building the view method using node! macro.

1impl App{
2    fn view(&self) -> Node<Msg>{
3        node!{
4            <div id="app" class="container">
5                <ul class="list">
6                    <li>"item 1"</li>
7                    <li>"item 2"</li>
8                    <li>"item 3"</li>
9                </ul>
10            </div>
11        }
12    }
13    // --snip--
14}

The first listing very closely resembles html code.

Listing 2: Building the view using function calls.

1impl App{
2    fn view(&self) -> Node<Msg>{
3        div([id("app"), class("container")], [
4            ul([class("list")],[
5                li([], [text("item 1")]),
6                li([], [text("item 2")]),
7                li([], [text("item 3")]),
8            ])
9        ])
10    }
11    // --snip--
12}

The second listing is a normal function call to build a DOM tree using the pattern.

1
2<tag_name>([<attributes>], [children_node])
3

The function name is the tag of the html. The first argument is an array/vec of attributes. The second argument is an array/vec of child nodes.

Attributes can be created using the pattern.

1
2<attribute_name>(value)
3

The function name is the attribute name and the first argument is the attribute value.

I personally prefer the 2nd option for 2 reasons.

  • cargo fmt for free, and aligns your code nicely.
  • The code is a bit shorter than using the macro syntax.