Flexible Twig Templates in Craft 3
Diving in, we look at how the Entry Handler Template works.
The first thing we see in the Entry template is that it is including another template.
{% include ["entry/" ~ entry.section.handle ~ "/" ~ entry.type,
"entry/" ~ entry.section.handle ~ "/default", "entry/default"] %}
Which one? Well that depends on the section and entry type. The include uses a set of templates — defined via variables — to hand the template layout off to the proper template.
Let’s say we are going to display a Link entry from the Blog section. The entry.twig
template will include the template entry/blog/link.twig
.
This link.twig
template extends another template (entry/default.twig
), which has some of the markup we need. This entry/default.twig
is generic is used by every type of field on the site.
After that the template defines a block called itemContent
and overrides it with the output of the linkDescription
field for that entry.
Over in the entry/default.twig
template there is a conditional that displays the entry title different if the Entry Type is link.
{% if entry.type == 'link' %}
<h2><a href="{{ entry.linkUrl }}">{{ entry.title }} ⇗</a></h2>
{% else %}
<h2><a href="{{ entry.url }}">{{ entry.title }}</a></h2>
<p class="post-date">{{ entry.postDate | date('M d, Y') }}</p>
{% endif %}
The entry/default.twig
template also extends the _layout.twig
template, which is the base layout for the entire site.
We now have a single template to which we point our Sections and the we leverage Twig to take it from there. This simplifies our approach so we don’t have to have multiple entry templates — one for each section — and instead leave the specificity for later on when we get lower in the template stack.
Flexible Twig Templates in Craft 3 is made up of the following videos: