Component-based Development
  • Welcome!
  • What you will build
  • Chapter 1
    • Local Setup
  • Chapter 2
    • Drupal theme and Front-End Tools
  • Chapter 3
    • Components architecture
    • Best practices
    • Drupal attributes
    • Twig embeds
  • Chapter 4
    • Building Components
      • Eyebrow
      • Heading
      • Button
      • Components Variations
      • Movie Card
      • Drupal Libraries
      • Featured Movie
      • Movie Card Collection
      • Movie List
      • Other components
  • Chapter 5
    • Building the back-end
      • Taxonomy
      • Image Styles
      • Content Types
      • View
      • Paragraph Type
  • Chapter 6
    • Integrating components
      • Movie Card
      • Featured Movie
      • Movie Card Collection
      • Movie List
      • Movie full display
  • Chapter 7
    • Resources
Powered by GitBook
On this page

Was this helpful?

  1. Chapter 3

Twig embeds

PreviousDrupal attributesNextBuilding Components

Last updated 6 years ago

Was this helpful?

The challenge we face is having control of the markup while adhering to Drupal's best practices for rendering content. When the time to integrate a component with Drupal comes, often times using include statements will do the job, but there are times when we want to modify content or markup before Drupal renders it and include statements don't allow for this. We could use the extend statements but these could also be limiting. In these situations the best option is to use Twig's embed statements, which combines both, include and extend functionality. Let's see an example.

<article class="card
  {{- attributes ? attributes.class -}}"
  {{- attributes ? attributes|without(class) -}}>
  {{ title_prefix }}
  {{ title_suffix }}
  ...
  {% block card_content %}
    {{ card_content }}
  {% endblock %}
</article>

We've declared a (not the same as Drupal's blocks), in which we are passing the card_content variable to print some content. The block on its own does nothing. Content will be rendered normally even if we do nothing with the block. The advantages of the twig block come when it's time to integrate the card component with Drupal.

{% embed '@patterns/card/card.twig' with {
    attributes: attributes,
    title_prefix: title_prefix,
    title_suffix: title_suffix,
    heading: heading,
    cover_image: content.field_main_image|render|trim is not empty ? content.field_main_image,
    card_content: content.card_content
  } only
%}
  {% block card_content %}
    <h3>This is a custom title</h3>
    {{ card_content }}
  {% endblock %}
{% endembed %}

This is a simple example of how we can use twig blocks to alter or update content before rendering. In this example we've added a new title above the card_content which the original component did not provide. There are so many other things we can do when we wrap things in twig blocks which gives us tremendous flexibility and control.

twig block