【问题标题】:How can I fetch/print the path or url of an entity reference to my twig template (Drupal 8)?如何获取/打印对我的树枝模板(Drupal 8)的实体引用的路径或 URL?
【发布时间】:2018-12-01 18:07:23
【问题描述】:

我一直在试图弄清楚如何使用实体引用来提取节点内容类型的 url。

显然使用{{ links.entity.uri }}{{ links.entity.url }} 不起作用

<div>

{% for links in node.field_related_items %}

    <h2>{{ links.entity.label }}</h2>
    <a href="{{ links.entity.uri }} " ></a>

{% endfor %}

</div>

【问题讨论】:

    标签: php drupal twig theming


    【解决方案1】:

    这对我有用:

    <a href="{{ links.entity.id }}"></a>
    

    这只会带你到/node/entity_id,而不是/entity_name/entity_id

    我想扩展这个答案,说你应该在你的.theme 文件中添加一个Drupal::entityQuery()。在此查询中,您需要获取作为内容链接的“别名”。在您的情况下,这将为您提供这些链接 /migrations/aboutiom

    这是一个可能看起来像的示例......

      function theme_name_preprocess_node(&$variables) {
        $query = \Drupal::entityQuery('node')
                      ->condition('status', 1)
                      ->condition('type', 'related_links')
        $nids = $query->execute();
        $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
        $related_links = [];
        foreach ($nodes as $item) {
          $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$item->id());
          $related_links[] = [
            'title' => $item->getTitle(),
            'id' => $item->id(),
            'field' => $item->get('field_name')->value,
            'alias' => $alias,
          ];
        }
        $variables['related_links'] = $related_links;
      }
    

    现在在你的树枝模板中你可以做这样的事情......

    {% for link in related_links %}
        <a href="{{ link['alias'] }}">{{ link['title'] }}</a>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多