Riot.js Loops
Jakob Jenkov |
Riot.js has a loop mechanism which can help you generate HTML from arrays of data. In this Riot.JS loop tutorial we will take a closer look at how the Riot.JS loop mechanism works.
You can loop through either an array of primitive data (strings, numbers etc.) or an array of objects. We will see how to do both in this tutorial.
Looping Through Simple Values
To use a Riot.JS loop you have to insert an each
attribute in the HTML element which
is to contain the HTML generated by the loop. This is inserted inside the Riot.JS tag definition, in the template HTML.
Here is an example Riot.JS tag definition that contains a loop:
<mytag> <h1>The Title</h1> <ol> <li each="{city in cities}">{city}</li> </ol> <script> this.cities = ["New York", "London", "Tokyo"]; </script> </mytag>
Notice the each
attribute inside the <li>
element. The value of this
attribute contains a Riot.js loop definition. The loop definition declares a loop that iterates the
cities
array. The element containing the loop definition plus all the HTML inside it
is repeated one time for each element in the cities
array.
During the loop each element in the cities
array is bound to
a variable named city
. The value of this variable is then inserted into the HTML
via the {city}
expression inside the <li>
element.
The value of the cities
array is set in the <script>
element
of the tag definition.
Looping Through Objects
Riot.JS can also loop through arrays of objects. You can use Riot expressions to access the properties of each object in the array. Here is an example:
<mytag> <h1>The Title</h1> <ol> <li each="{city in cities}">{city.name} - {city.country}</li> </ol> <script> this.cities = [ { name : "Shanghai" , country:"China" } ,{ name : "Seoul" , country:"South Korea" } ,{ name : "Moscow" , country:"Russia" } ]; </script> </mytag>
Notice the two expressions {city.name}
and {city.country}
. These expressions
access the name
and country
properties of each object in the cities
array.
Riot.JS contains a shorthand for iterating arrays of objects and accessing the object properties. Here is an example:
<mytag> <h1>The Title</h1> <ol> <li each="{cities}">{name} - {country}</li> </ol> <script> this.cities = [ { name : "Shanghai" , country:"China" } ,{ name : "Seoul" , country:"South Korea" } ,{ name : "Moscow" , country:"Russia" } ]; </script> </mytag>
Notice how the loop definition now only lists the name of the array - cities
.
When looping through an array of objects this way, the properties of each object are bound to
variables with the same name as the property name. Thus, instead of referring to city.name
and city.country
you can now just refer to name
and country
,
just like the example does.
Tweet | |
Jakob Jenkov |