Last active
April 16, 2019 14:03
-
-
Save andy-blum/756bdc8cf2a15ab746cc8e8099975ede to your computer and use it in GitHub Desktop.
Useful/Tricky Twig Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Merge attributes onto a link | |
* | |
* 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({'#options': {'attributes': {'class': ['some', 'class', 'here']}}}) }} | |
{% endfor %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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