在节点树枝模板drupal中获取自定义内容类型的字段

时间:2021-02-17 08:14:30

标签: drupal drupal-8 drupal-modules

我开发了一个自定义内容类型,其中包含一些很好用的自定义字段,我还为其分配了一个模板。问题是我无法根据模板中的帖子访问这些字段。让我给你看看我的代码

[module].module

 <?php
    function [module]_theme($existing, $type, $theme, $path)
    {
        return [
            'node__[module] => [
                'variables' => [],
            ]
        ];
    }

模板/节点--[模块].html

<h1>Uneeb</h1>

下面是我创建并想在树枝模板中访问的字段的 yml 文件

[module]/config/install/field.field.node.[module].location.yml

# field.field.node.cspace.location.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.location
    - node.type.cspace
  module:
    - text
id: node.cspace.location
field_name: location
entity_type: node
bundle: cspace
label: 'Script Location'
description: 'More specific information about the car brand'
required: true
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  display_summary: false
field_type: text_with_summary

节点模板工作得很好我可以在页面上显示文本 uneeb 并且仅针对我现在最初想要的这种特定内容类型我想针对这种内容类型访问数据。我尝试了很多解决方案但没有似乎工作正常,但我无法访问 Twig 模板中的自定义内容字段,有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

首先,您需要将 base hook 添加到您的主题声明中:

    function [module]_theme($existing, $type, $theme, $path)
    {
        return [
            'node__[module]' => [
                'variables' => [],
            ],
            'base hook' => 'node'
        ];
    }

然后在您的 node--[module].html.twig 中,您可以像这样打印内容字段:

{{ content.field_xyz[0] }}

field_xyz 是字段的机器名称。