-
Notifications
You must be signed in to change notification settings - Fork 70
When to use include, extends, and embed
Because Drupal 8 leverages Twig, we have multiple ways of passing components into templates, namely include
, extends
and embed
. Below we'll walk through usage of each. First we'll walk through include
and embed
using Emulsify's link component as an example.
{% set link_base_class = link_base_class|default('link') %}
<a
{{ bem(link_base_class, (link_modifiers), link_blockname) }}
{% for attribute,value in link_attributes %}
{{ attribute }}="{{ value }}"
{% endfor %}
href="{{ link_url }}"
>
{% block link_content %}
{{ link_content }}
{% endblock %}
</a>
Include
is the simplest form of requiring a component in a template. It allows you to pass the content of a component into a template, replacing variables. See below for an example:
{% include "@atoms/01-links/link/link.twig" with {
link_content: "Click here to go to fourkitchens.com",
link_url: "https://www.fourkitchens.com",
} %}
This will output: <a class="link" href="https://www.fourkitchens.com">Click here to go to fourkitchens.com</a>
See templates/content/page-title.html.twig
for an example of include
in Emulsify.
Embed
is the most robust Twig statement for including a component inside a template. It allows you to include the component's contents, pass variables to that component, and replace the contents of Twig blocks. See below for an example using the same link component:
{% embed "@atoms/01-links/link/link.twig" with {
link_blockname: "image",
link_url: "http://google.com",
} %}
{% block link_content %}
{% include "@atoms/04-images/00-image/_image.twig" with {
"img_src": "http://placeimg.com/1200/800/tech",
} %}
{% endblock %}
{% endembed %}
This will output:
<a class="image__link" href="http://google.com">
<img class="img" src="http://placeimg.com/1200/800/tech">
</a>
As you can see embed
gives us a lot of possibilities. We can include the contents of the link component, change variables within it and also replace Twig blocks within that.
See templates/content/node--article--teaser.html.twig
for an example of embed
in Emulsify.
Like embed
, extends
allows you to include the contents of another template and replace Twig blocks. However, you cannot replace variables in the component you're including using extends
. You also cannot have markup outside of your Twig blocks in a template that extends another whereas with embed
you can do both of those things.
See components/_patterns/05-pages/_page.twig
for an example of extends
in Emulsify.
- Home
- Basics
- Examples
- Environment-specific or Special Instructions
- Acknowledgements
- To-do
- Contribute to this Wiki!