Objectives & prerequisites
Objectives
- List Twig's arithmetic operators
- Explain the difference between division and integer division
- Explain what the modulo operator does
Prerequisites
- Working with
{{ }}and{% %}tags. - Basic programming concepts (variables, operators)
Last revision:
Operators
| Operator | Operation | Example usage | Output |
| + | addition | {{ 5 + 2 }} | 7 |
| - | subtraction | {{ 7 - 5 }} | 2 |
| * | multiplication | {{ 6 * 8 }} | 48 |
| / | division | {{ 9 / 2 }} | 4.5 |
| // | integer division | {{ 9 // 2 }} | 4 |
| % | module / remainder | {{ 9 % 2 }} | 1 |
| ** | power / exponentiation | 5 ** 3 | 125 |
Working with expressions
Needless to say this works with expressions as well:
{% set prices = { 'full': 20, 'discounted': '12' } %}
{% set exponent = 2 %}
{{ prices.discounted ** exponent }}Output:
144Operator precedence
Twig syntax for arithmetic operations operator precedence follows PHP's operator precedence.
When in doubt, use braces:
{{ 5 * 3 - 2 }}
{{ (5 * 3) - 2 }}
{{ 5 *(3 - 2) }}Output:
13
13
5Summary
- Twig supports all basic arithmetic operations.
- Twig respects PHP's rules for operator precedence.