Tags
apply
The apply
tag lets you use filters on a block of template data:
{% apply upper %}
This text becomes uppercase
{% endapply %}
This means the text "This text becomes uppercase" will be transformed to uppercase when rendered.
for
The for
loop lets you iterate over each item in a sequence. Here's a deeper dive into its functionalities:
Basic Looping:
To display a list of users:
Users:
{% for user in users %}
- {{ user }}
{% endfor %}
Using the ..
Operator:
This operator can help you iterate over a sequence of numbers or letters:
{% for i in 0..10 %}
- {{ i }}
{% endfor %}
{% for letter in 'a'..'z' %}
- {{ letter }}
{% endfor %}
Special Variables in for
Loop:
Inside a for
loop, you can access:
loop.index
: Current iteration (1 indexed)loop.index0
: Current iteration (0 indexed)loop.revindex
: Iterations from the end (1 indexed)loop.revindex0
: Iterations from the end (0 indexed)loop.first
: True if it's the first iterationloop.last
: True if it's the last iterationloop.length
: Number of items in the sequenceloop.parent
: The parent context
{% for user in users %}
- {{ loop.index }}: {{ user }}
{% endfor %}
Iterating Over Keys or Keys and Values:
{% for key in users|keys %}
- {{ key }}
{% endfor %}
{% for key, user in users %}
- {{ key }}: {{ user }}
{% endfor %}
Iterating Over a Subset:
To loop over a subset of values, use the slice
filter:
Top Ten Users:
{% for user in users|slice(0, 10) %}
- {{ user }}
{% endfor %}
if
The if
statement allows you to test if an expression evaluates to true.
Simple Conditions:
To test if an expression evaluates to true:
{% if online == false %}
The website is in maintenance mode. Please, come back later.
{% endif %}
Testing Non-Empty Arrays:
{% if users %}
{% for user in users %}
- {{ user }}
{% endfor %}
{% endif %}
Using the not
Operator:
{% if not user.subscribed %}
User is not subscribed to the mailing list.
{% endif %}
Combining Conditions with and
and or
:
{% if temperature > 18 and temperature < 27 %}
It's a nice day for a walk in the park.
{% endif %}
Multiple Branches with elseif
and else
:
{% if product.stock > 10 %}
Available
{% elseif product.stock > 0 %}
Only {{ product.stock }} left!
{% else %}
Sold-out!
{% endif %}
macro
Macros can be likened to functions in most programming languages. They provide a mechanism for reusing template fragments, ensuring that there's no unnecessary repetition in your code.
Example:
{% macro currencyFormat(amount, currencySymbol = "$") %}
{{ currencySymbol }}{{ amount|number_format(2, '.', ',') }}
{% endmacro %}
{% macro discountPrice(originalPrice, discountPercentage) %}
{{ originalPrice * (1 - discountPercentage/100)|number_format(2, '.', ',') }}
{% endmacro %}
{% macro formatDate(dateString, format = "Y-m-d") %}
{{ dateString|date(format) }}
{% endmacro %}
Every argument passed to a macro can have a default value.
set
You have the capability to assign values to variables. These assignments utilize the set
tag and can target multiple variables simultaneously.
Basic Variable Assignment:
Assign the value 'bar' to the variable foo
:
{% set foo = 'bar' %}
Subsequently, foo
becomes available in the template:
{# displays 'bar' #}
{{ foo }}
Variable Assignment with Expressions:
The value assigned can be any valid expression:
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
Multiple Variable Assignments:
You can assign to multiple variables simultaneously:
{% set foo, bar = 'foo', 'bar' %}
{# This is equivalent to: #}
{% set foo = 'foo' %}
{% set bar = 'bar' %}
Capturing Chunks of Text:
The set
tag can be utilized to capture chunks of text:
{% set foo %}
...
{% endset %}
Loop Scope:
Loops are scoped. This means a variable declared inside a loop isn't accessible outside:
{% for item in list %}
{% set foo = item %}
{% endfor %}
{# foo will NOT be accessible here #}
However, to make the variable available outside, you should declare it prior to the loop:
{% set foo = "" %}
{% for item in list %}
{% set foo = item %}
{% endfor %}
{# Now, foo is accessible here #}
verbatim
The verbatim
tag serves to delineate sections as raw text, ensuring they are not parsed. This can be particularly useful when you wish to showcase template syntax as an example within a template. Here's an illustrative snippet:
{% verbatim %}
{% for item in items %}
- {{ item }}
{% endfor %}
{% endverbatim %}
with
The with
tag is utilized to create an inner scope. Any variables defined within this scope will not be visible outside of it.
Basic Usage:
{% with %}
{% set foo = 42 %}
{{ foo }} {# foo is 42 inside this block #}
{% endwith %}
Outside the block, the variable foo
will no longer be accessible.
Defining Variables with a Hash:
You can also define the variables at the beginning of the with
scope by passing a hash:
{% with { foo: 42 } %}
{{ foo }} {# foo is 42 inside this block #}
{% endwith %}
Again, outside the block, the variable foo
will not be visible.
Using Expressions that Resolve to a Hash:
This technique works with any expression that resolves to a hash:
{% set vars = { foo: 42 } %}
{% with vars %}
...
{% endwith %}
Limiting Visibility with the only
Keyword:
By default, the inner with
scope has access to the outer scope context. If you wish to limit the inner scope to only the variables defined within it, use the only
keyword:
{% set bar = 'bar' %}
{% with { foo: 42 } only %}
{# Inside this block, only the foo variable is defined. #}
{# The bar variable is not accessible. #}
{% endwith %}
Last updated