Skip to content

When to use include, extends, and embed

Evan Willhite edited this page Dec 6, 2018 · 6 revisions

Using Components in Templates

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') %}

  {{ 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 %}

Twig Include {% include "@atoms/path/to/file.twig" %}

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",
  link_url: "",
} %}

This will output: <a class="link" href="">Click here to go to</a>

See templates/content/page-title.html.twig for an example of include in Emulsify.

Twig Embed {% embed "@atoms/path/to/file.twig" %}{% endembed %}

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: "",
} %}
  {% block link_content %}
    {% include "@atoms/04-images/00-image/_image.twig" with {
      "img_src": "",
    } %}
  {% endblock %}
{% endembed %}

This will output:

<a class="image__link" href="">
  <img class="img" src="">

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.

Twig Extends {% extends "@atoms/path/to/file.twig" %}

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.

You can’t perform that action at this time.