Skip to content

Instantly share code, notes, and snippets.

@andy-blum
Last active April 16, 2019 14:03
Show Gist options
  • Save andy-blum/756bdc8cf2a15ab746cc8e8099975ede to your computer and use it in GitHub Desktop.
Save andy-blum/756bdc8cf2a15ab746cc8e8099975ede to your computer and use it in GitHub Desktop.
Useful/Tricky Twig Snippets
/*
* Merge attributes onto an image
*
* Note: Attributes must have at least one non-null value.
* If you don't have a value, enter an single-space string (' ').
*/
{% for item in items %}
{{ item.content|merge({'#item_attributes': {'attribute-name': ['attribute', 'values', 'here']}}) }}
{% endfor %}
/* Test & set/print based on true or false */
boolean ? val_if_true : val_if_false
/* Test and set/print only if true */
boolean ? val_if_true
/* Test and set/print only if false */
boolean ?: val_if_false
/* Test and set/print value if not undefined/NULL */
testValue ?? fallback
/*
* Conditional Addition of classes using Ternary/Null-Coalescing Operator
*/
{% set classes = [
is_front ? 'page--front': 'page--internal',
has_parent ? 'child-item',
is_teaser ?: 'full-node',
randomVar ?? fallbackValue
] %}
/*
* Conditional printing
*/
<div data-view-mode="{{ is_teaser ? "teaser" : "full" }}">
<p>Lorem ipsum</p>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment