Get node ID or URL bằng template preprocess field FIELD NAME
20th Jun 2022You 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 %} 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}) }}
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 }}
Add new comment