0

We have several fields on our Article content type, one of which is a Link field. In a twig template we would like to display a <section> such that all of it is clickable with different fields inside of it.

Current node--article.html.twig

<section>
  <a href={{ url }}>{{ label }}</a>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
</section>

Modified node--article.html.twig template to make entire <section> clickable (desired output).

<a href={{ url }} >
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
</a>

Is there another way I should be doing this?

I was looking for something similar to below. It would output what is under the Modified node--article.html.twig (above)

{{ link(label, url)|insert(content.body, content.field_subtitle, content.field_category) }}

2 Answers 2

1

I don't see anything for the insert tag in Twig or Drupal, but you can preprocess the url variable in mytheme.theme and pass it to the template, giving you what you want:

<a href="{{ url }}" >
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
</a>

The url variable would be created in the preprocess function.

If its a standard link field, you could try:

$link = $node->get('field_link')->getValue();

if (!$external) {
  $variables['url'] = Url::fromUri($link['uri'])->toString();
}
else {
  $variables['url'] = $link['uri'];
}

Edit: totally forgot the line that checks if it is external.

0

You can use something like {{ node.field_link.0['#url'] }} to get the absolute value of a url in a link field.

You can use {{ dump(_context) }} temporarily to get exact array key names and values out of twig debug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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