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?
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?
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 }}
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 %}
node
would be nice. But from a security point of view there's no difference.