Tutorials     About     RSS
Tech and Media Labs

Riot.js Expressions

Jakob Jenkov
Last update: 2017-05-16

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:


this.title = "This is inserted with an expression";


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:

	<h1>RiotJS Expression Example</h1>

	<span>{val * 10}</span>

		this.val = 5;

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:



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 (_).

Jakob Jenkov

Featured Videos

Thread Congestion in Java - Video Tutorial

Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC