I have some drupal 8 sites that make heavy use of the Paragraphs and Bootstrap Paragraphs modules.

Some of my users want to be able to create anchor style links to specific paragraph items on pages. For example; a user may wish to link directly to a specific accordion that is halfway down the page. They may wish to do this either from the body of the same page or with an anchor style hyperlink from elsewhere on the site. eg: mysite.com/mypage#myanchor

Other than adding a "name" field and creating a specific "anchor link" twig override for every paragraph type and field is there a more straightforward way of doing this?

In messing around with the anchor_link module It seems it can only find anchors in the body of a node. If you add an anchor to say, the body of an accordion the link function cannot see it.


First you need to set up an ID for the paragraphs. You can do this in oko_preprocess_paragraph():

 * Implements template_preprocess_paragraph().
function THEME_preprocess_paragraph(&$variables) {
  $variables['paragraph_id'] = $variables['paragraph']->id();

Now, you can output the ID of the paragraph using {{ paragraph_id }} in any paragraph templates you have. So you can copy paragraph.html.twig to your theme, and change this:

<div{{ attributes.addClass(classes) }}>

To this:

<div{{ attributes.addClass(classes) }} id="paragraph-{{ paragraph_id }}">
| improve this answer | |
  • 2
    For a one file solution you could also add the ID to attributes in preprocess or access {{ paragraph.id }} in the template directly. – 4k4 Jul 2 '19 at 6:11
  • Nowdays, id must be collected with id() method, so it becomes: {{ paragraph.id() }}. – MilanG Mar 27 at 10:24
  • Nice. You should put that as an answer, I’ll upvote it. – Jaypan Mar 27 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.