Set tag

{% set foo = "bar" %}
{% set foo, bar = arr %}
{% set <identifier> %}
  content
{% end %}

The {% set %} tag can be used to set the value of a variable in the current scope to a given value, to the value of the tag's contents, or to unpack an array variable. It's best described with an example.

Example

First, the simplest form:

{% set foo = "bar" %}
{{ foo }}

This would simply output the string "bar". You can of course also do more complicated logic, like:

{% set foo = 1 + 2 %}
{{ foo }}

This would output "3", as you would expect.

You can also use set to expand an array variable, like so:

{% set foo, bar = arr %}
foo = {{ foo }}
bar = {{ bar }}

Assuming the follow code:

  CarrotEngine engine = new CarrotEngine(...);

  Bindings bindings = new SingletonBindings("arr", new int[] { 123, 456 });
  System.out.println(engine.process("filename.html", bindings));

You'll get the following output:

foo = 123
bar = 456

Finally, the "block" form of {% set %}, given the template:

{% set foo %}
  Here is some <b>HTML</b>!
{% end %}

This would set the value of the variable foo to the string "Here is some <b>HTML</b>!". Later on in your template, you can then do stuff like:


  {{ foo }}
  {{ html.safe(foo) }}

And get:


  Here is some <b>HTML</b>!
  Here is some HTML!