Twig Code Blocks - Introduction

Prerequisites
  • Basic experience with programming concepts (variables, functions, conditions, loops, arrays, objects).
Last revision:

Code blocks

As a template language, Twig also has features found in programming languages.

Using the {% %} delimiters you can insert code blocks and do things like:

  • declaring and updating variables
  • string manipulation
  • arithmetic operations
  • logical operations
  • control structures (if-then-else statements)
  • iterations (looping over lists, performing actions until a condition is met)
  • includes (include and/or inherit from other templates)

Throughout this unit you will learn how to perform all these types of operations.

However,  it's not because you can add a lot of custom programming logic to your templates, that you should. The recommended practice is that most of the logic should happen in PHP before the data is sent to the template. Extensive data manipulation inside Twig templates should only happen as a last resort.

Remember: if you can perform the manipulations earlier as part of custom PHP code, you should most likely do so.

With that said, let's learn to program in Twig.