Skip to content

Instantly share code, notes, and snippets.

@davebeach
Last active November 8, 2016 06:18
Show Gist options
  • Save davebeach/1598f12cb56da40fdab0c11a8be6fdbc to your computer and use it in GitHub Desktop.
Save davebeach/1598f12cb56da40fdab0c11a8be6fdbc to your computer and use it in GitHub Desktop.

Various Twig Tips and Tricks

Content

Content Without Title Field

It is possible to pass the content without the title printing. Without title:``` {{ content|without('field_title') }}

With title:```
{{ content| }}

Security Considerations

XSS Injection Attacks

The Escape Filter

All variables that can come from a user input, must be escaped through the escape filter. {{ test|e("html_attr") }}

The autoescape choices are:

{{ variable|e("css") }} // For escaping variables that will be inserted into CSS
{{ variable|e("js") }} // For escaping variables that will be inserted into js
{{ variable|e("url") }} // For escaping variables that will be inserted into a URL
{{ variable|e("html_attr") }} // For escaping variables that will be inserted into an HTML attribute (ie. class).

Inject Into HTML

{% autoescape 'html' %}
<p class="{{ variable|clean }}"></p>  
{% endautoescape %}

Alternatively you can append variable = {{ variable |clean_class }

And of course you can escape each special character, which sometimes is a bad idea. Generally do not manually escape to something that is being injected into an HTML attribute. Otherwise manual esaping is available.

Where as if between tags than you just autoescape the special characters.
<p class=\"test\"\>{{ variable|e('http_attr") }}</p>

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