Skip to content

Instantly share code, notes, and snippets.

@geoffyuen
Last active October 10, 2019 14:45
Show Gist options
  • Select an option

  • Save geoffyuen/9a75713a922439edf2ecafccd32f032d to your computer and use it in GitHub Desktop.

Select an option

Save geoffyuen/9a75713a922439edf2ecafccd32f032d to your computer and use it in GitHub Desktop.
Twig Tips and Tricks

Twig Tips and Tricks

Output tricks

Echo variables and math

{% set name = 'Hello Buddy' %}
{{ "Hi #{name}, how are you today" }}
{{ "A math operation =  #{(1 + 2) * (4 * 5)}" }}

Do something if for loop is empty

{% for user in users %}
  <li>{{ user.username|e }}</li>
{% else %}
  <li><em>no users available</em></li>
{% endfor %}

Extend a block instead of replacing it with parent

{% block toolbar %}
  {# The content of the base.html.twig will be retrieved and printed in this inherited view too#}
  {{ parent() }}
  <a href="path_to_something">
    User Normal Action 3
  </a>
  <a href="path_to_something">
    User Normal Action 4
  </a>
{% endblock %}

Output json and indented json

{% set data = {
    "Hey": "Ho",
    "What": 12,
    "Value" : true
}%}

{{ data|json_encode()|raw }}

{{ data|json_encode(constant('JSON_PRETTY_PRINT'))}}

Add a function to twig (instead of using fn('my-function'))

class StarterSite extends TimberSite {
	function add_to_twig($twig){
		/* this is where you can add your own fuctions to twig */
		$twig->addExtension(new Twig_Extension_StringLoader());
		$function = new Twig_SimpleFunction('my_twig)function', function ($my_var) {
			// do your stuff here with $my_var
		});
		$twig->addFunction($function);
		return $twig;
	}

}

new StarterSite();

Collected from:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment