Template Suggestions

Exercise: Debugging the Teaser

  • In your Drupal site, visit the page you created before with the 50/50 teaser.

  • Right-click anywhere on the teaser and select Inspect or inspect element, depending on your browser. This will display the HTML that makes up the page you are currently viewing. In addition, it will display other information generated by Twig debugging. See an example of Twig debug output below (click on it to zoom in):

Inspecting the 50/50 teaser

If you look at the image above, you will see a few things that are extremely helpful for creating the right template suggestions:

  • The last line of green text BEGIN OUTPUT... shows where the template being used by Drupal to render the Teaser is located and what its name is modules/contrib/block_content_template/templates/block-content.html.twig.

  • Just above that line, under FILE NAME SUGGESTIONS:, there is a list of files all of which begin with block-content. Since we are using the Block Content Template module, for the teaser, Drupal is telling us we can create a Twig template with any of the names listed above and we can customize it to our needs. This list is what we mean when we say Template suggestions.

  • The file with an x next to it is the template Drupal is currently using to render the Teaser.

Exercise: Creating new template suggestions

We will need to store our custom templates somewhere. To make things convenient we place our component presenter templates in the component folder itself. So in our example we will create a subdirectory inside of the "teaser" component folder.

Steps:

  1. Create a folder named "templates" in your teaser component folder.

  2. Create a blank file named block-content--teaser.html.twig. Now every time the 50/50 component is rendered, Drupal will use this new template and not the one provided by our contributed module.

  3. Next clear Drupal's cache (Configuration > Development > Performance)

  4. Reload the page and inspect the code one more time (Right-click on Teaser and select Inspect).

Inspecting our 50/50 teaser with a blank template

Notice there is an x next to block-content--teaser.html.twig, which means Drupal is now using our custom twig template suggestion. In addition, notice the path of the template is now our own theme's component's sub-directory.

Last updated