Monday, 20 August 2018

How to render fields on node twig templates?

It is easy way to render node fields on node template. We just have to create template file according to content type machine name like 'landing page' is content type, So machine name will be 'landing_page', but our template name will be 'node--landing-pages--full.html.twig' as per Drupal 8(Symphony) Syntax.

and we will call/render fields like..


Node id: {{ node.id }} // Node id

Node Url: {{ url }}  // current page url

Node Title: {{ label }}  // Node title

Node Bundle: {{ node.bundle }}  // Node bundle its means content type name

Node Publish Status: {{ node.isPublished() }}  // Retrun node is published or not

Node Created Time: {{ node.getCreatedTime() }}  //will return node created timestamp

Node Plain(Text) Field: {{ node.field_machine_name.value }}  //will return node plain field value

Node Image: {{ file_url(node.field_full_banner_image.entity.fileuri) }} or {{ file_url(node.field_full_banner_image.entity.uri.value) }}  // show url of full banner image is the image field in node

Node Description/body: {{ content.body }}

Node Link field: {{ node.field_machine_name.0.url }}

Node Link Field Title Value: {{ node.field_machine_name.0.title }}

Node custom field: {{ content.field_machine_name }}  or {{ content.field_machine_name[0] }}  // ex:{{ content.field_resources_content_type }}

If you want to check field value return or not the we have multiple options like.
// here we are checking field banner video return or not.
{% if content.field_banner_video|render %}  
  // write comment here..
{% endif %}

OR

// here we are checking field carousel title is empty or not.
{% if content.field_carousel_title[0] is not empty %}
  // write comment here..
  {{ content.field_carousel_title[0] }}
{% endif %}


Split array in twig:

We have split option also in twig file in symphony, please have a look.
{% set videogal_value_variable = videogall|split('~~') %}
like 'videogall' is an array and separated by ~~ sign so we will do like this for break and use.
{{ videogal_value_variable.0 }}
{{ videogal_value_variable.1 }}
and so on.


Note: If have any suggestions or issue regarding 'How to render fields on node twig templates' then you can ask by comments.

1 comment:

How to resolve max execution time error in drupal ?

When you found error regarding 'max_execution_time' exceed, then you can follow steps for resolve this error: Steps:   You can put t...