I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).

How can I get the URL or at least the ID on field level, to create that link?

  • 1
    Do you mean the ID of the entity (node) that the field that's being rendered is attached to? – Clive Jul 17 '19 at 13:13

The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:

{{ path('entity.node.canonical', {'node':  element['#object'].id}) }}
  • Would this also work if the same field is coincidentally used by another entity type (Paragraph) at the same time? Not sure if this is possible at all... – leymannx Jul 17 '19 at 13:21
  • 1
    You wouldn't put this code in a generic field.html.twig, but in a template name suggestion targeting a specific field. If you have the same field name in different entities you can still target the specific one by adding the entity type to the template name. – 4k4 Jul 17 '19 at 13:29

You should maybe preprocess you the URL in place. Via template_preprocess_field get the node ID, build the path alias, send it to Twig.

 * Implements template_preprocess_field__FIELD_NAME().
function MYTHEME_preprocess_field__MYFIELD(&$variables) {

  if ($variables['element']['#entity_type'] === 'node') {
    $node = $variables['element']['#object'];
    $nid = $node->id();
    $variables['myurl'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);

In field.html.twig then do:

{% if myurl %}
   <a href="{{ myurl }}">Kool Keith</a>
{% endif %}
  • Is there any disadvantage (e.g. security) including the URL via element['#object'] without preprocessing (like suggested in the answers above)? – Benjamin Jul 17 '19 at 13:25
  • @Benjamin – That's what I asked under @4k4's answer. I guess fields can be shared across entities (but not sure about that), then an additional check for node would be nice. But from a security point of view there's no difference. – leymannx Jul 17 '19 at 13:29

Without preprocessing, directly in Twig:

{# get owner entity #}
{% set owner_entity = element['#object'] %}
{# render id #}
id = {{ element['#object'].id }}
{# render raw field value #}
field foo = {{ element['#object'].field_foo.0.value }}

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.