Using partial Twig templates is a great way to organise your frontend code because you can reuse code fragments in multiple templates. But what happens if you want to use the same partial template in multiple places and customise its content slightly?
You can do this by passing variables to the included partial template using the with
keyword.
Here is an example of including a partial Twig template using the with
keyword to pass it a variable:
Background: partial twig templates
Partial Twig templates help you reduce code duplication by adding code in a template and including it in multiple other templates. To find out more, check out my tutorial on partial Twig templates.
An example
I recently implemented a paywall for a membership site where people had to log in to view certain articles and book on events. For this to work, there is a box that consists of a login form, links to become a member (if you aren’t already) and some intro text to explain why they need to log in. Everything in this box was the same for articles and events except for the intro text.
All the code for the box is contained in a single partial Twig template, called paywall.html.twig
. This template is then included where needed in other templates, such as the node template for articles and events.
The full snippet for paywall.html.twig is:
To include this partial template in the node template, I can use the following:
This will add the same markup when I include it in both the event and article node template. In order to customise it, I can use the with keyword to pass in a variable. In this case, I want to customise the title. That way, I can change the title on events and content templates so they are different.
On events node template, I will use the following for the title:
And on the article node template, I can use the following for the title:
Then all you need to do is add title
as a variable in paywall.html.twig.
This code snippet:
<h3>Please sign in</h3>
Will become:
<h3></h3>
The full snippet for paywall.html.twig is:
When this is rendered, the H3 for articles will become:
Wrapping up
Using partial templates is a fantastic way to organise your code base and reuse fragments of template code. Using the with
keyword takes this one step further by allowing you to customise your partial Twig templates depending on where it is used.