php - 如何获取/打印对我的 Twig 模板 (Drupal 8) 的实体引用的路径或 url?

标签 php drupal twig theming

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

enter image description here

显然使用 {{ 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>

最佳答案

这对我有用:

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

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

我想通过说您应该将 Drupal::entityQuery() 添加到您的 .theme 文件来扩展这个答案。在此查询中,您需要获取作为内容链接的“别名”。在您的情况下,这将为您提供这些链接 /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;
  }

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

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

关于php - 如何获取/打印对我的 Twig 模板 (Drupal 8) 的实体引用的路径或 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984948/

相关文章:

php - 使用 INNER JOIN 在 3 个表中搜索关键字

mysql - Drupal 数据库结构 - 高效/低效?

symfony - 如何在其他模板的同一目录中扩展 Twig 模板?

templates - Symfony 2 中的模板部分

php - 重定向后 Codeigniter session 数据丢失

遍历 HTML 文件以查找其中所有图像的 PHP 代码?

php - Ajax无限滚动当没有更多结果时停止

php - 仅显示当前帖子的分类术语 (Drupal)

php - 交叉引用 2 个表并获得结果

php - 如何解析 symfony2 中非 Controller 类中的路径