{set}

Assigns one or more variables, as globals that outlive the level the tag stands in.

Variables and stores Single tags

Syntax

{set $name = value}
{set $name = value, $other = value}

Parameters

$name = value
One or more assignments, separated by commas. The value is an expression: a literal, a field, arithmetic ($price * $qty), a comparison.

Description

{set $name = value} evaluates the value and assigns it to a global variable, which every tag after it can read as {$name}. Several assignments go in one tag, separated by commas. The tag prints nothing.

The assignment sticks: a {set} inside a loop, an {if} or any other level outlives it, so a loop can add up a total that is still there after the loop. That is the difference with a $name = value written on another tag - {orders $n = 5} - which is that level's own and is unwound when the level closes, and with %name = value, which is set again for every occurrence.

The values of one {set} are evaluated before any of them is assigned: in {set $a = 1, $b = $a + 1} the $a on the right is the value from before the tag (an error when there was none). Write two {set} tags when one value builds on another.

Under the strict syntax check a {set} written as a pair, or one whose words hold no $name = value assignment (a missing $, a missing value), is an error. To count, {increment} and {decrement} are shorter; to keep a list or a piece of template, {data} and {content}.

Examples

Assigning values

Literals and expressions, several in one tag; a second set reads the first.

Templateexamples/set/1-assign.pad
{set $item = 'Notebook', $price = 4.50, $qty = 3}
{set $total = $price * $qty}
<p>{$qty} &times; {$item} at {$price} = {$total}</p>
Resultopen alone

3 × Notebook at 4.50 = 13.5

A total that outlives the loop

A set inside a loop sticks; a variable written on the loop tag itself is unwound when the loop ends.

Templateexamples/set/2-sticks.pad
{set $sum = 0, $note = 'before'}
{sequence '1..4', name='num', $note = 'inside'}
  {set $sum = $sum + $num}
  <p>{$num}: running total {$sum}, note {$note}</p>
{/sequence}
<p>After the loop: total {$sum}, note {$note}</p>
Resultopen alone

1: running total 1, note inside

2: running total 3, note inside

3: running total 6, note inside

4: running total 10, note inside

After the loop: total 10, note before

See also

  • {increment} Adds one to a variable, starting it at 1 when it does not exist yet.
  • {decrement} Takes one off a variable, starting it at -1 when it does not exist yet.
  • {data} Turns its content - JSON, XML, YAML, CSV, a list or a range - into a named data set for a later tag to iterate.
  • {content} Keeps a piece of template under a name instead of printing it, for a later {name} to render.