Skip to content

Instantly share code, notes, and snippets.

@migliori
Last active February 13, 2024 06:31
Show Gist options
  • Save migliori/332fb35f1ebaf98ac5bc78bc31570c12 to your computer and use it in GitHub Desktop.
Save migliori/332fb35f1ebaf98ac5bc78bc31570c12 to your computer and use it in GitHub Desktop.
Twig Cheatsheet #twig #cheatsheet
$twig = new Twig_Environment($loader, array('debug' => DEBUG));
///////////////
// Variables //
///////////////
$twig->addGlobal('session', $_SESSION);
---
$template->render(array('nav' => $nav));
---
{{ constant('MY_CONSTANT') }}
---
{{ item.text|raw }}
---
{% set foo = 'foo' %}
---
{% set foo = '<small>' ~ item.foo ~ '</small>' %}
---
{% set r = session.rubrique %}
{% set rubrique = attribute(session.tableau_categories, r) %} // = session.tableau_categories.r
---
{{ dump(item) }}
//////////////
// Comments //
//////////////
{#
Comment
#}
///////////
// Loops //
///////////
{% for item in nav.items %}
{% endfor %}
{% for i in range(0, object.records_count - 1) %}
{{ object.name[ loop.index0 ] }}
{% endfor %}
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
---
/////////////////
// Conditional //
/////////////////
{% if item.dropdown|length > 0 %}
{% endif %}
{% if item.prop|trim is (not) empty %}
{% endif %}
{% if item.condition == true %}
{% endif %}
{% if item.prop is defined %}
{% endif %}
{% if (item.condition == true and item.condition2 == true) or item.condition3 %}
{% endif %}
////////////
// Format //
////////////
{{ 9800.3456|number_format(2, '.', ' ') }} {# outputs : 9 800.34 #}
// set default format for number_format
$twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setNumberFormat(2, '.', ' ');
// or $twig->getExtension('core')->setNumberFormat(2, '.', ' '); depending on Twig version
{{ 9800.3456|number_format }} {# outputs : 9 800.34 #}
////////////
// Dump //
////////////
$twig = new Twig_Environment($loader, array(
'debug' => true,
// ...
));
$twig->addExtension(new Twig_Extension_Debug());
<pre>
{{ dump(user) }}
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment