The if and for instructions are used to execute code based on a condition and to iterate over a slice, i.e. a sequence of elements of the same type.
The if instruction executes the code inside it if the condition is true. For example, the following instruction:
{% if stock > 10 %}
High availability
{% end %}
High availability
shows "High availability" only if the stock quantity is greater than 10.
The condition of the {% if condition %} instruction can be of any type. This is different from the if condition in Go, which can only be boolean.
If you want to execute one block of code or another based on a condition, you can write:
{% if stock > 10 %}
High availability
{% else %}
Low availability
{% end %}
High availability
Scriggo also supports the else if form:
{% if stock > 10 %}
High availability
{% else if stock > 0 %}
Low availability
{% else %}
Not available
{% end %}
High availability
The for instruction lets you iterate over a slice (essentially a sequence of elements of the same type), assigning each element to a variable.
For example, if the products variable is a slice of Product, the following example shows the names of all contained products:
{% for product in products %}
<div>{{ product.Name }}</div>
{% end %}
The product variable is implicitly declared and has the same type as the elements of products. It is also visible only inside the for instruction.
The for in instruction is one of the different forms of the for instruction and is the only one not present in the Go language.