TransWikia.com

Twig Template print field - if not node number

Drupal Answers Asked by Juc1 on December 28, 2021

I can print an image field in my node template like this:

{{ content.field_big_image }}

But can I say "print this field but not if the node number is node/45" ?

One Answer

Yes. Sometimes themes will drop documentation when they override a template, but you can always check the original template file for the available variables and other info relevant for working with the template. If you check the node.html.twig template provided by the node module in core, you'll see the following documentation at the top of the file.

/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - node.getCreatedTime() will return the node creation timestamp.
 *   - node.hasField('field_example') returns TRUE if the node bundle includes
 *     field_example. (This does not indicate the presence of a value in this
 *     field.)
 *   - node.isPublished() will return whether the node is published or not.
 * 
 * ... continued ...
 *
 */

Note the relevant info here:

The node entity [is available] with limited access to object properties and methods. Only method names starting with "get", "has", or "is" and a few common methods such as "id", "label", and "bundle" are available.

This means you can access the node id with node.id.

So, you can print your field on nodes other than your specific node by wrapping your field in a conditional like:

{% if node.id != 45 %}
  {{ content.field_big_image }}
{% endif %}

or

{% if not node.id == 45 %}
  {{ content.field_big_image }}
{% endif %}

Either choice should produce the same result.

Answered by sonfd on December 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP