Get node ID or URL bằng template preprocess field FIELD NAME

20th Jun 2022
Table of contents

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 %}
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 }}
Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.