Reuse Twig templates from CERN Components inside other templates

Hi Drupal developers,

I am building a theme based on CERN Clean and I would like to create a template for basic pages that will be able to use parallax without using Paragraphs (i.e. adding a simple image field and showing it just using the same markup as the Row component + Background component).

The question is: can I just ‘call’ these templates from my template, to avoid duplicating code? Of course I would have to pass parameters to them to override their variables with my image URL etc. I’ve seen this is possible on the documentation for Twig (https://twig.symfony.com/doc/2.x/tags/include.html), but not sure how this plays out in Drupal, especially with templates outside the theme’s folder.

In Drupal, we have some documentation about this, which I will try now: https://www.drupal.org/docs/8/theming-drupal-8/including-part-template and also this: https://www.drupal.org/project/components

I’ll see if I can use that technique and see if {% include "@cern_components/molecules/row/row.html.twig" %} or something the like would work, and keep you updated.

The alternative would be to copy/paste the markup on my template just to reuse the CSS styles without involving too much logic, but I feel that would be not very DRY.

I would like to know if you have experience with this and already have a recipe :slight_smile:

Thanks in advance!

1 Like

I have bad news about this: I cannot reuse these templates since they are designed to work only with Paragraphs, thus requiring customization to be able to work with simple fields.

The alternative of course is to use a Paragraph myself on the page, so the templates will be loaded automatically, but I believe this is overkill just for a banner image (from the perspective of a content maintainer), so in the end I just added simple markup on my template and used CSS to style it up.

Also, the disadvantage of the method I was trying to use is that you need to know the implementation details of the Twig templates that you need to use. This means access to the code base for CERN Components (based on the UI Patterns API).

I hope this information is useful to someone, and I’m looking forward to read about other strategies.

Hello Oscar,

I didn’t fully understand what you try to implement but in general the components re-use patterns designed to be used with Display Suite. The latter means that you can re-use the patterns for different view modes, including custom content types/paragraphs etc. In this way, you will avoid re-writing code and also the websites look more consistent.

I am currently writing the documentation on how to re-use the patterns on websites that use the components and the CERN Theme.

Let me know if you have any questions on that.

Kostas

1 Like

Hi @kplatis,

thanks for the info, I will try using the Display Suite layouts, I didn’t think about that.

When I have time I’ll try and give feedback.

Thanks!