Symfony Twig Cheatsheet

Twig is a straight forward templating engine you can use in Symfony and even on its own. Here are some useful snippets, patterns and tips to get more usefulness out of creating your templates and views.

TWIG accessing global values:

Skip if a value wasn’t defined or doesn’t exist (avoid errors for unset values):

Conditional if a cookie is set, show:

Output Twig templates as strings:

Click here for more details:
send variable to Twig template and output HTML UNESCAPED:

Iterating through Twig values

Loop and add an incrementing index independent of data, just as a view representation for ordering.

Extra Tip: If loop.index needs to be indexed starting with zero, you need to use “loop.index0” instead of “loop.index” below.

Accessing arrays with indexes based on value of index within a loop:

In the above example, an array called $labelKeysArr could have different indexes that are keys based on the value indexVal.  Let’s say $labelKeysArr[1]=”Mailing Address” and indexVal=1, then the snippet above would show “Mailing Address”.

Get referer url from twig.

Works with other header values as well.

Twig Debugging

Twig comes with its own Debug extension to allow you to troubleshoot variables within a Twig template using a similar verbose function like var_dump.

First, add the following to your /app/config/config_dev.yml (be sure not to do this in the standard config.yml, which is the production environment):

Now inside your Twig templates you can “var_dump” variables using the built-in Twig Debug:

Twig extended debugging and troubleshooting

Adding a Twig extension used to be with the “extensions” property but is now deprecated:

The newest way of adding extensions is through services using tags to let your setup learn that these services are twig.extensions and they need to be called when twig related services are executed. Just drop this into our config.yml to make this work and also have the debug parameter on your config.yml set to true:

Another note: I recommend PHP Storm for your IDE if you are using Symfony and Twig. It is the best combination that will save you a lot of development time by highlighting many more errors through its logic and understanding of the PHP language. It is also very helpful for editing YAML files, since if you are a single indentation off or you inadvertently saved your YAML file with some tab characters, PHP Storm is intuitive enough to save you a lot of time when writing code.

– Aaron Belchamber
Aaron Belchamber’s Marketing & Video Services Website

One thought on “Symfony Twig Cheatsheet

Leave a Reply

Your email address will not be published. Required fields are marked *