Jump to heading Twig
Twig Tweak drupal modules provides a lot of helpers to work with Drupal content in twig templates.
Please check out the cheatsheet to know more.
Jump to heading Twig Filters
Filters that work on Drupal's Field render array on entity templates.
clean_unique_idGets an unique id suitable for html ids.render_field('field_name')Renders a single field from a render-array of an entity.
Jump to heading Twig Functions
Jump to heading
asset_path
This will return the path to the current theme-folder, suitable to reference static assets.
Example:
<img src="{{ asset_path }}/assets/images/logo.svg" />
Jump to heading Best practices
Jump to heading Entity templates
Declare a block in the entity-base template and make sure to render the cache tags in the base template.
Entity base template:
{% block content %}
{{ content }}
{% endblock %}
{# make sure to render cache tags #}
{{ content|cache_metadata }}
This approach allows you to move all base functionality into the base template, and just expose a block/slot for the actual content.
For a bundle-class template see below.
Jump to heading Iterating through referenced entities
Here's a snippet to iterate over a field with referenced entities and pass them to a child component. It also showcases how to render a single field from the referenced child
{# This code would be in the parent template #}
{% extends "paragraph.html.twig" %}
{% block content %}
{# Load referenced child items into memory. #}
{% set children = content.field_accordion_items|children(true) %}
{# Loop through each item and map values as expected inside the parent component. #}
{% set list = children|map((child, key) => {
title: child | render_field('field_accordion_item_title'),
id: ('tab-' ~ (key + 1))|clean_unique_id,
content: child,
}) %}
{% include '@patterns/accordion/accordion.html.twig' with {items: list} only %}
{% endblock %}