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) }}
0

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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