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:

For $_POST variables use this :
{{ app.request.parameter.get("page") }}

For $_GET variables use this :
{{ app.request.query.get("page") }}

For $_COOKIE variables use this :
{{ app.request.cookies.get("page") }}

For $_SESSION variables use this :
{{ app.request.session.get("page") }}

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

{# Skip prototype if form was submitted else fields will show up twice #}
{% if form.contactInfoApp.address1 is not defined %}

Conditional if a cookie is set, show:

{% if app.request.cookies.has(‘acceptCookies’) %} Yes you accept cookies {% endif %}

Output Twig templates as strings:

$loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
$template = $twig->loadTemplate('index.html');
echo $template->render(array('template' => 'variables', 'set' => 'here'));

Click here for more details: http://symfony.com/doc/current/reference/dic_tags.html#twig-loader
send variable to Twig template and output HTML UNESCAPED:

{% if formMessage is defined %}
{{ formMessage|raw }}
{% endif %}

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.

{% for comment in comments %}
Comment {{ nameComments[[ loop.index ]] }} : “{{ comment[['description']] }}”
{% endfor %}

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

{{ attribute(array['labelKeysArr'],entity.indexVal) }}

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.

app.request.headers.get(‘referer’)

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):

twig:
debug: 1
services:
debug.twig.extension:
class: Twig_Extensions_Extension_Debug
tags: [[{ name: 'twig.extension' }]]

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

 {% debug nameOfVariable %}

Twig extended debugging and troubleshooting

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

extensions: [[twig.extensions.debug]]

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:

twig:
debug: %kernel.debug%

// Here's the code for the extensions:

services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
– { name: twig.extension }
twig.extension.debug:
class: Twig_Extensions_Extension_Debug
tags:
– { name: twig.extension }

// Call on var_dump according to documentation:
{% debug variableForDumping %}

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

1 thought on “Symfony Twig Cheatsheet

Leave a Comment

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