Display Array Variables: data-f-repeat
The data-f-repeat attribute allows you to automatically loop over a referenced variable. The most common use case is in time-based models, like those written in SimLang or Vensim, when you want to report the value of the variable at every time step so far. The data-f-repeat attribute automatically repeats the DOM element it's attached to, filling in the value.
To display a DOM element repeatedly based on an array variable from the model:
- Add the
data-f-repeatattribute to any HTML element that has repeated sub-elements. The two most common examples are lists and tables. - Set the value of the
data-f-repeatattribute in the HTML element you want to repeat to the name of the array variable. - Optionally, you can use templates (
<%= %>) to reference theindex(for arrays) orkey(for objects) andvalueto display. Theindex,key, andvalueare special variables that Flow.js populates for you.
Examples:
For example, to create a table that displays the year and cost for every step of the model that has occurred so far:
<table>
<tr>
<td>Year</td>
<td data-f-repeat="Cost[Products]"><%= index + 1 %></td>
</tr>
<tr>
<td>Cost of Products</td>
<td data-f-repeat="Cost[Products]"></td>
</tr>
</table>In the third step of the model, this example generates the HTML:
<table>
<tr>
<td>Year</td>
<td data-f-repeat="Cost[Products]">1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>Cost of Products</td>
<td data-f-repeat="Cost[Products]">100</td>
<td>102</td>
<td>105</td>
</tr>
</table>You can also use this with a <div> and have the <div> itself repeated. For example:
<div data-f-repeat="sample_array"></div>generates:
<div data-f-repeat="sample_array">2</div>
<div>4</div>
<div>6</div>Notes:
- You can use the
data-f-repeatattribute with both arrays and objects. If the model variable is an object, reference thekeyinstead of theindexin your templates. - The
key,index, andvalueare special variables that Flow.js populates for you. - The template syntax is to enclose each keyword (
index,key,variable) in<%=and%>. Templates are available as part of Flow.js's lodash dependency. See more background on working with templates. - In most cases the same effect can be achieved with the
data-f-foreachattribute, which is similar. In the common use case of a table of data displayed over time, thedata-f-repeatcan be more concise and easier to read. However, thedata-f-foreachallows aliasing, and so can be more useful especially if you are nesting HTML elements or want to introduce logic about how to display the values.