简体   繁体   中英

Getting fields of a custom content type in node twig template drupal

I have developed a custom content type with some custom fields which works nice, I have also assigned a template to it.The Problem is I cannot access the fields against the post in my template. let me show you my code

[module].module

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

templates/node--[module].html

<h1>Uneeb</h1>

below is the yml file of field i created and want to access in twig template

[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

the node template works perfectly fine I can the text uneeb on the page and only for this specific content type which i originally wanted now I want to access data against this content type.I have tried a bunch of solutions but none of them seems to be working and I cannot access my custom content fields inside twig template can anyone help me out?

First you need to add base hook to your theme declaration:

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

Then in your node--[module].html.twig , you can print content field like this:

{{ content.field_xyz[0] }}

with field_xyz is machine name of the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM