Last active
October 4, 2022 08:10
-
-
Save newtone/c3e33985d67a6b75bd5bcd11793590de to your computer and use it in GitHub Desktop.
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
# how to get the raw field value in a twig template? | |
{{ entity.field_name.value }} to get the true raw value, includes tags and encoding. | |
Example: {{ node.body.value }} | |
result: <p>Batman & Robin</p> | |
{{ content.field_name.0 }} to get the raw value minus tags and encoding. | |
Example: {{ content.body.0 }} | |
result: Batman & Robin | |
## with Twig Field Value module | |
{{ content.field_name|field_value }} | |
# How to trim body text (field_body) | |
## 1. Use |raw to output the html as html, may produce malformed tags: | |
{% set text = content.field_body|render %} | |
{{ text|length > 200 ? text|slice(0, 200)|raw ~ '...' : text|raw }} | |
## 2. Strip html first, cleaner: | |
{% set text = content.field_body|render|striptags %} | |
{{ text|length > 200 ? text|slice(0, 200) ~ '...' : text }} | |
# Check if field is empty | |
{% if content.field_name %} | |
## OR, if there is some unexpected output then this: | |
{% if content.field_name|render is not empty %} | |
{% content.field_name %} | |
{% endif %} | |
## manual image style | |
{% for item in content.field_card_image['#items'] %} | |
{% set image = { | |
'#theme': 'image_style', | |
'#style_name': 'medium', | |
'#uri': item.entity.uri.value, | |
'#alt': item.alt, | |
'#width': item.width, | |
'#height': item.height | |
} %} | |
{{ image }} | |
{% endfor %} | |
# more info on twig if: https://www.drupal.org/forum/support/theme-development/2016-02-22/twig-if-and-contentfield | |
# get Language | |
{% if language == 'en' %} | |
{{ "Do something" }} | |
{% else %} | |
{{ "Do something else" }} | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment