Riot.js Expressions
Jakob Jenkov |
Riot.js expressions are small snippets of JavaScript-like code which can be embedded in HTML. These JavaScript snippets makes it easier to generate HTML based on data inside Riot.js tags. This tutorial will take a closer look at Riot.js expressions.
A Simple Riot.js Expression
To see how Riot.js expressions look, here is a simple Riot.js expression example:
<mytag> <h1>{title}</h1> <script> this.title = "This is inserted with an expression"; </script> </mytag>
This example shows a Riot.js tag definition with a Riot.js expression inside.
The expression part of the above example is the {title}
part inserted inside the <h1>
element. Riot.js will evaluate this expression when the tag is defined.
The expression inserts the value of the title
variable at the location of the expression.
The title
variable is set inside
the <script>
tag further down in the element, in the this.title = "...";
statement.
Riot.JS Expressions Evaluate to Values
Riot.JS expressions evaluate to values, meaning the expression inside the { }
will be
evaluated to a value. It is this value that is inserted at the place of the { }
in the HTML page.
Riot.JS expressions can evaluate JavaScript-like expressions to values. For instance,
{2 + 2}
will evaluate to 4
which is then inserted into the HTML page where the
{2 + 2}
expression is located.
You can also perform calculations on JavaScript variables inside expressions. Here is an example:
<mytag> <h1>RiotJS Expression Example</h1> <span>{val * 10}</span> <script> this.val = 5; </script> </mytag>
This example sets the JavaScript variable val
to 5
and writes the
val * 10
(which is 50
) into the HTML page using the expression
{val * 10}
.
Riot.js Options
You can pass values into a tag from where the tag is used via tag attributes. In the example above with the
<mytag>
tag, you can pass values to it when it is used, like this:
<mytag myvalue="This is an attribute value"></mytag>
This attribute value can now be accessed inside a Riot.js expression like this:
<mytag> <h1>{opts.myvalue}</h1> </mytag>
Riot.js will now insert the attribute value of the myvalue
attribute inside the
<h1>
element.
Note: The browser converts all attribute names to lowercase, so myValue
would be converted to
myvalue
internally in the DOM. Thus you could not access it via opts.myValue
,
but only via opts.myvalue
(lowercase attribute name). To avoid naming case mistakes like this
just stick to lowercase attribute names. Words in attribute names can instead be separated with
underscores (_).
Tweet | |
Jakob Jenkov |