Flexible Twig Templates in Craft 3

Reviewing the Entry Handler Template

Diving in, we look at how the Entry Handler Template works.

The first thing we see in the Entry tem­plate is that it is includ­ing anoth­er template. 

{% include ["entry/" ~ entry.section.handle ~ "/" ~ entry.type, 
"entry/" ~ entry.section.handle ~ "/default", "entry/default"] %}

Which one? Well that depends on the sec­tion and entry type. The include uses a set of tem­plates — defined via vari­ables — to hand the tem­plate lay­out off to the prop­er template.

Let’s say we are going to dis­play a Link entry from the Blog sec­tion. The entry.twig tem­plate will include the tem­plate entry/blog/link.twig.

This link.twig tem­plate extends anoth­er tem­plate (entry/default.twig), which has some of the markup we need. This entry/default.twig is gener­ic is used by every type of field on the site.

After that the tem­plate defines a block called itemContent and over­rides it with the out­put of the linkDescription field for that entry.

Over in the entry/default.twig tem­plate there is a con­di­tion­al that dis­plays the entry title dif­fer­ent if the Entry Type is link.

{% if entry.type == 'link' %}
	<h2><a href="{{ entry.linkUrl }}">{{ entry.title }} &neArr;</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 tem­plate also extends the _layout.twig tem­plate, which is the base lay­out for the entire site.

We now have a sin­gle tem­plate to which we point our Sec­tions and the we lever­age Twig to take it from there. This sim­pli­fies our approach so we don’t have to have mul­ti­ple entry tem­plates — one for each sec­tion — and instead leave the speci­fici­ty for lat­er on when we get low­er in the tem­plate stack.

Flexible Twig Templates in Craft 3 is made up of the following videos: