Question

I created "figure" Paragraphs type, which contains an image field and a caption field. How (from start to finish) do I specify in HTML/twig how to render this new Paragraphs type?

As an example, how would I specify that the output would generate following code?

<figure>
  <img src="image">
  <figcaption>caption</figcaption>
</figure>
Was it helpful?

Solution

In Drupal, the specifying the generation of HTML from Paragraph types (as well as other types in Drupal) is done via the misnomer "theming."

  • First create a sub-theme.
  • Next, copy the /modules/contrib/paragraphs/templates/paragraph.html.twig file into your sub-theme's templates folder and name it paragraph--figure--default.html.twig.
  • Add the following code below the set classes closing brace %} which specifies the parameters for the image you'd like to display.

    {%
      set imagestyle = {
        '#theme':      'image_style',
        '#style_name': 'large',
        '#uri':        content.field_image['#items'].entity.uri.value,
        '#alt':        content.field_image['#items'].entity.alt,
        '#attributes': { class: 'myimage' },
      } 
    %}
    
  • Last, replace {{content}} with the code below:

    <figure>
        {{ imagestyle }}
        <figcaption>{{ content.field_caption }}</figcaption>
    </figure>
    

Note: Using {{ content.field_image }} directly inside <figure> instead of specifying a structure with theme image_style will not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top