Skip to content

Instantly share code, notes, and snippets.

@newtone
Created May 31, 2022 14:30
Show Gist options
  • Save newtone/1b74cbbc8eb09edb4a5ea86ac95d1fe4 to your computer and use it in GitHub Desktop.
Save newtone/1b74cbbc8eb09edb4a5ea86ac95d1fe4 to your computer and use it in GitHub Desktop.
{# https://alextade.me/ #}
{# Drupal Theming - Twig cheat sheet - Useful practical examples twig file. #}
{# Date #}
{% set createdDate = node.getCreatedTime|date('j M Y') %}
<div class="datewrap">{{ createdDate }}</div>
{# OR #}
{{ node.getCreatedTime|format_date('gr') }}
<time datetime="{{ node.getCreatedTime|format_date('datetime') }}">{{ node.getCreatedTime|format_date('gr') }}</time>
{# end #}
{# use field's value as a HTML data-* Attribute. field_wtext is the fields machine name #}
<div data-wtext="{{ content.field_wtext.0 }}" data-imgfirst="{{ content.field_imgfirst.0 }}" data-bkgcolor="{{ content.field_bkgcolor.0 }}">
</div>
{# end #}
{# print only the raw value-text of node title #}
{{ node.label }}
{# end #}
{# print only the field label #}
<h3>{{ node.field_wtext.label}}</h3>
{# end #}
{# print only the field value #}
{{ node.field_ingred.value|raw }}
{# end #}
{# print addtoany to twig template file #}
<div class="field--label-above socialwrap">
<div class="field__label">{{ "Share" | t }}</div>
{{ content.addtoany }}
</div>
{# end #}
{# set classes based on field values or if have value, also for boolean fields #}
{%
set classes = [
'node',
'node--type-' ~ node.bundle|clean_class,
not node.isPublished() ? 'node--unpublished',
view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
node.field_layout.value ? node.field_layout.value|clean_class,
node.field_integer.value ? 'lay-' ~ node.field_integer.value,
node.field_thumb.value ? 'withumb',
not node.field_thumb.value ? 'nothumb',
node.field_boxes.value ? 'boxes',
node.field_hex.1.value ? 'gradbkg',
node.field_cat.value ? 'taxname-' ~ node.field_cat.entity.name.value,
node.field_cat.value ? 'taxid-' ~ node.field_cat.0.target_id,
]
%}
<article{{ attributes.addClass(classes) }}>
<p>....</p>
</article>
{# end #}
{# human readable content type name in a node template #}
{{ node.type.entity.label }}
{# end #}
{# link to home page #}
<a href="{{ url('<front>') }}">{{ 'Home'|t }}</a>
{# end #}
{# taxonomy-term--collections.html.twig , taxonomy-term--pages.html.twig , twig templates file name suggestion #}
{# views-view-unformatted--bkgs.html.twig , views-view--bkgs.html.twig , twig templates file name suggestion #}
{# link to current content & how to print its title #}
<h2><a href="{{ url }}" rel="bookmark">{{ label }}</a></h2>
{# end #}
{# translatable text inside twig template file #}
<a class="rmore" href="{{ url }}" rel="bookmark">{{ "Read more" | t }}</a>
<a class="teamore" href="projects">{{ 'Go to projects page'|t }}</a>
{# end #}
{# Get username & user id in custom user twig template #}
{{ user.name.0.value }}
{{ user.uid.0.value }}
{# or #}
{{ user.uid.value }}
{# end #}
{# if/else/elseif statements in twig #}
{% if content.field_image[0] is not empty %}
{% elseif content.field_url[0] is empty %}
{% else %}
{% endif %}
{% if (content.field_title[0] is not empty or content.body[0] is not empty) %}
{% endif %}
{% if content.field_url[0] is empty %}
{% endif %}
{% if (content.field_big[0] is not empty) or (content.body[0] is not empty) %}
{% endif %}
{% if (content.field_promblock[0] is empty) and (content.field_full[0] is empty) %}
{% endif %}
{% if (content.field_imgs[0] is not empty) and (node.field_lay.value != "5") %} {# if not equal to value != #}
<div class="side">
{{ content.field_imgs }}
</div>{# end side #}
{% endif %}
{# end #}
{# if/else inside views custom text field, field "Output format" -> Custom -> Custom output for FALSE don't type anything #}
{% if field_more is not empty %}
<h2 class="atitle"><a href="{{ view_node }}">{{ title }}</a></h2>
{% else %}
<h2 class="atitle">{{ title }}</h2>
{% endif %}
"{{ field_name }} {{ field_surname }}","{{ mail }}"{% if field_phone is not empty %},"{{ field_phone }}"{% endif %}{% if field_country is not empty %},"{{ field_country }}"{% endif %}
{# end #}
{# if node have specific taxonomy term (id) #}
{% if node.field_tags.0.target_id == "31" %} {# if news #}
|&nbsp; <time datetime="{{ node.getCreatedTime|format_date('datetime') }}">{{ node.getCreatedTime|format_date('gr') }}</time>
{% endif %}
{# end #}
{# if contains (in) a string #}
{% if '24' in content.field_layout[0] %}
<div class="placeholder"></div>
{% else %}
{# end #}
{# check a boolean value in twig templates #}
{% if node.field_zomo.value == "1" %}
<div class="zomo">
{% trans %}Lorem ipsum.{% endtrans %}
</div>
{% endif %}
{# end #}
{# check if boolean is checked #}
{% if node.field_3colay.value %}
{{ content.field_simgs.1 }}
{% else %}
{{ content.field_simgs }}
{% endif %}
{# end #}
{# check if node has a specific taxonomy term #}
{% if (node.field_tags.0.target_id == "30") or (node.field_tags.0.target_id == "31") %}
{{ node.field_tags.entity.name.value }}
{% endif %}
{# end #}
{# check a Number (integer) value if 1 or more-plural #}
<span>( {{ node.field_days.value }}
{% if node.field_days.value == 1 %}
day
{% else %}
days
{% endif %}
)</span>
{# end #}
{# h2 title on views / h1 on its page #}
{% if content.field_bigtext[0] is not empty %}
{% if not page %}
<h2 class="ptitle">{{ content.field_bigtext }}</h2>
{% else %}
<h1 class="ptitle">{{ content.field_bigtext }}</h1>
{% endif %}
{% endif %}
{% if label and not page %}
<h2 class="atitle">{{ label }}</h2>
{% else %}
<h1 class="atitle">{{ label }}</h1>
{% endif %}
{# end #}
{# use the url of a link field as a link in twig #}
<a href="{{ node.field_link.0.url }}">
{{ content.field_image }}
</a>
{# end #}
{# print blocks in regions twig templates region--footer.html.twig #}
{{ elements.agth_main_menu }}
{{ elements.languageswitcher }}
{# end #}
{# use field's value as a css class #}
<div class="slimgs {{ content.field_slidpos[0] }}">
{# end #}
{# Check if it's the front page in the template #}
{% if is_front %}
<h3><a href="{{ url }}" rel="bookmark">{{ label }}</a></h3>
{% else %}
<h2><a href="{{ url }}" rel="bookmark">{{ label }}</a></h2>
{% endif %}
{# end #}
{# Check if is logged in #}
{% if logged_in %}
<p>logged in</p>
{% else %}
<p>not logged in</p>
{% endif %}
{# end #}
{# get field's raw value, no (stript) html tags #}
<span data-nurl="{{ url }}" data-nid="{{ node.id }}" data-ntitle="{{ node.field_btitle.value|striptags }}" class="nodenavl"></span> {# node #}
<article data-history-node-id="{{ node.id }}">
<a class="rmore2" href="{{ url }}">{{ 'Go to'|t }} {{ term.name.value }}</a> {# taxonomy name #}
<a class="rmore" href="{{ term.field_url.value }}">{{ 'Learn more'|t }}</a> {# taxonomy field #}
<h2 class="field_btitle">
{% set btitle %}
{{ content.field_btitle }}
{% endset %}
{{ btitle|striptags('<p>') }}
{# btitle|striptags('<p>')
doesn't work, do it with js-jquery
$('.blo .field--name-field-stitle').find('p').contents().unwrap();
for https://validator.w3.org/nu/ do it better on drupal wysiwyg editor allowed tags (not p!) #}
{{ btitle|striptags }} {# this work #}
</h2>
{# end #}
{# get media id #}
<article{{ attributes.addClass(classes).setAttribute('data-mid', media.id) }}>
</article>
{# end #}
{# media--image.html.twig overide media theme template and add a link to image #}
{% if content.field_url[0] is not empty %}
<a class="medialink" href="{{ media.field_url.value|raw }}">
{{ content.field_media_image }}
</a>
{% else %}
{{ content.field_media_image }}
{% endif %}
{# end #}
{# Different print based on different view modes of taxonomy.
This is because we couldnt use the name suggestions node--article--teaser.html.twig like in content types
taxonomy-term--services.html.twig #}
{# You could use "set classes" 2 first examples in views-view--taxonomy_term.html.twig template file,
if you also do -> https://www.drupal.org/project/views/issues/1099490#comment-13255741 #}
{%
set classes = [
'vocab-' ~ term.bundle|clean_class,
term.bundle|clean_class ~ '-' ~ term.id,
view_mode|clean_class,
term.field_thumb.value ? 'withumb',
not term.field_thumb.value ? 'nothumb',
]
%}
<div{{ attributes.addClass(classes) }}>
{{ title_prefix }}
{{ title_suffix }}
{% if view_mode == 'logo' %}
<a class="taxlogo" href="{{ url }}">
{{ content.field_logo }}
</a>
{% endif %}
{% if view_mode == 'teaser' %}
<a class="taxlink" href="{{ url }}">
<div class="taxteasertext">
<h2>{{ name }}</h2>
{{ content.field_logo }}
</div>
{{ content.field_taxbkg }}
{{ content.field_taxbkg2 }}
</a>
{% endif %}
{% if view_mode == 'full' %}
<div class="flexwrap">
{{ content.field_taxside }}
<div class="textwrap">
<div class="textwrapin">
<h1 class="taxtitle">{{ name }}</h1>
{{ content.description }}
</div>
</div>
</div>
{% endif %}
</div>
{# end #}
{# custom url links, get the base path #}
{# https://www.drupal.org/project/twig_link_attributes #}
{% if view_mode == 'bread' %}
{% set furl = url('<front>')|render %}
<a{{ attributes.setAttribute('href', furl ~ 'industries/#tax-' ~ term.id) }}>{{ name }}</a>
{% endif %}
<a{{ attributes.setAttribute('href', url ~ '#block-book').addClass('booknow2') }}>BOOK NOW</a>
<div class="breadcr">
{% set furl = url('<front>')|render ~ '/products/all' %}
<a href="{{ url('<front>') }}">{{ 'HOME'|t }}</a> &gt; <a href="{{ furl }}">{{ 'PRODUCTS'|t }}</a> &gt; {{ content.field_cat }}
</div>
{% set turl = url('<front>')|render ~ '/' ~ term.field_url.value %}
<h2><a class="atitle" href="{{ turl }}">{{ 'For'|t }} {{ term.name.value }}</a></h2>
{# end #}
{# check if a field has a value equal to something #}
{% if node.field_hstyle.value == "layout3" %}
<div>layout3</div>
{% endif %}
{# integer field check #}
{% if node.field_lay.value == "3" %}
layout 3
{% else %}
not layout 3
{% endif %}
{# end #}
{# Check user-access or user-role in node.html.twig #}
{% if user.hasPermission('administer nodes') %}
{% else %}
{% endif %}
{# end #}
{# print only the first value of a multi-field #}
{{ content.field_imgs.0 }}
{{ node.field_multxt.1.value }}
{# end #}
{# print the url of an image field so to be attached as a css backgound image #}
<a rel="bookmark" href="{{ node.field_link.0.url }}" style="background-image:url({{ file_url(node.field_bkg.entity.fileuri) }})">
{# end #}
{# print sidebar only if exists #}
{% if page.sidebar %}
<aside>
{{ page.sidebar }}
</aside>
{% endif %}
{# end #}
{# multi values files #}
{# ONLY content.field_bkgimgs.1 work for media fields. NOT node.field_bkgimgs.0.value #}
{{ content.field_multext.0 }}
{{ content.field_multext.1 }}
{{ node.field_multxt.0.value }}
{{ node.field_multxt.1.value }}
{% if content.field_multext.1 is not empty %}
{{ content.field_multext.1 }}
{% endif %}
{# end #}
{# Multi-level variable and combining syntaxes #}
{{ content.field_image.0['#item'].alt }}
{# end #}
{# Classes and Attributes in Twig Templates examples #}
{# Chaining methods #}
<article{{ attributes.addClass(classes).setAttribute('data-rid', node.id).setAttribute('data-lay', content.field_lay.0).setAttribute('data-lay2', node.field_lay.value).setAttribute('data-hex', node.field_hexbkg.value) }}>
<div{{ attributes.addClass(classes).setAttribute('id', 'id-' ~ node.id).setAttribute('data-hex', term.field_hex.value).setAttribute('data-history-node-id', node.id) }} > {# taxonomy twig #}
<div{{ attributes.setAttribute('id', 'myID').addClass(classes).removeClass('node--type-article').addClass('new-class') }}>
Classes and Attributes in Twig Templates Example 1
</div>
<div{{ attributes.removeClass('node--promoted') }}>
Classes and Attributes in Twig Templates Example 2
</div>
<div{{ attributes.setAttribute('data-value', 'something').removeAttribute('id') }}>
Classes and Attributes in Twig Templates Example 3
</div>
<div class="{{ attributes.class }} my-custom-class"{{ attributes|without('class') }}>
<p>With or without you</p>
</div>
{% if attributes.hasClass('new-class') %}
<p>New class exist!</p>
{% endif %}
{# end #}
{# Reusing templates - twig code #}
{# txtwrap.html.twig #}
<div class="txtwrap">
<div class="txtwrap2">
{{ title_prefix }}
{% if content.field_stitle[0] is not empty %}
{% if label and not page %}
<h2 class="atitle">{{ content.field_stitle }}</h2>
{% else %}
<h1 class="atitle">{{ content.field_stitle }}</h1>
{% endif %}
{% endif %}
{{ title_suffix }}
{{ content.body }}
{{ content.field_links }}
</div>
</div>{# end txtwrap #}
{# end txtwrap.html.twig #}
{# node--blo.html.twig #}
{% include directory ~ '/templates/txtwrap.html.twig' %}
{# end node--blo.html.twig #}
{# end #}
{# Loops and Iterators in Twig, my test #}
<ul>
{% for item in classes %} {# "classes" is the array variable that you want to print #}
{% if loop.index is divisible by(3) %} {# Use the special loop variable "loop.index" to determine index of the loop. #}
<li class="third-class">{{ item|upper|reverse }}</li> {# Twig filters, https://twig.symfony.com/doc/3.x/filters/index.html #}
{% else %}
<li>{{ item }}</li>
{% endif %}
{% endfor %}
</ul>
{% for item in items %}
{% if loop.first %} {# Use the special loop variable to determine when this is the first or last iteration and add new first/last classes to the appropriate list items. #}
<div{{ item.attributes.addClass(['field__item', 'first-tag']) }}>{{ item.content }}</div>
{% elseif loop.last %}
<div{{ item.attributes.addClass(['field__item', 'last-tag']) }}>{{ item.content }}</div>
{% else %}
<div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
{% endif %}
{% endfor %}
{% for item in items %}
{# {% if loop.index == 3 %} My test example #}
{% if loop.index is divisible by(3) and not loop.last %} {# OR more advanced #}
<div{{ item.attributes.addClass(['field__item', 'third-tag']) }}>{{ item.content }}</div>
{% else %}
<div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
{% endif %}
{% endfor %}
{# end #}
{# In a Twig template of korth theme we attach the library befilters.
in korth.libraries.yml
befilters:
js:
js/befilters.js: {}
dependencies:
- core/jquery
- core/jquery.once
#}
{{ attach_library('korth/befilters') }}
{# check node id #}
{% if node.id == 2 %}
{{ attach_library('korth/test') }}
{% endif %}
{% if (node.id != 15) and (node.id != 28) and (node.id != 32) %} {# if not About Me, Current Work, Teaching #}
<h2 class="atitle">{{ label }}</h2>
{% endif %}
{% if ( (content.body[0] is not empty) or (content.field_links[0] is not empty) ) and (node.id != 28) %}
<div class="txtwrap2">
{{ content.body }}
{{ content.field_links }}
</div>
{% endif %}
{# end #}
{# set variables #}
{% set name = 'Alex Tade' %}
{# print variables #}
<h1>Hello {{ name }}</h1>
{# dumb variables #}
{# Discovering-Inspect variables in a template #}
{{ dump() }} {# dump function without arguments #}
{# Prefer this way #}
{{ dump(_context|keys) }} {# 1. View all the available variables #}
{{ dump(classes) }} {# 2. inspect a certain variable with dump function #}
{# dump(classes) print that classes variable is array with 5 values. To print the first value #}
{{ classes[2] }} {# as normaly do with arrays #}
{# {{ dump(node) }} #}
{# dump(node) print that node variable is an object. To print the id, if found this 'id' => string '2' (length=1) #}
{{ node.id }} {# as normaly do with arrays or objects #}
{# end #}
{# twig filters #}
{{ name|upper }}
{% filter upper %}
<p>My name is {{ name }}</p> {# All this become uppercase, more at https://twig.symfony.com/ #}
{% endfilter %}
<div> &copy; {{ 'now'|date('Y') }}</div> {# Twig functions, https://twig.symfony.com/doc/3.x/filters/index.html #}
<p>{{ classes|safe_join(", ") }}</p> {# Drupal-specific filters #}
{# end #}
{# How to remove html markups on twig template #}
{% set conBody %}
{{ content.body }}
{% endset %}
{{ conBody|striptags }}
{# end #}
{# twig loops, look also https://twig.symfony.com/doc/2.x/tags/for.html (The loop variable!) #}
{% for i in 0..10 %}
{{ i }}
{% endfor %}
{% for letter in 'a'..'z' %}
{{ letter }}
{% endfor %}
{# end #}
{# Multi-level and combining syntaxes, image attributes #}
{{ content.field_image.0['#item'].alt }} {# Alt attribute #}
{{ content.field_image.0['#item'].width }} {# Width attribute #}
{{ content.field_image.0['#item'].height }} {# Height attribute #}
{# end #}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment