Score:1

Conditionally display headers on web page in page.html.twig

mx flag

We have a header which contains a secondary menu on top bar, search, main menu and logo in page.html.twig.

We would like to implement a new header with quite a few changes and so would like to add a bool field or some field, somewhere for example all Content Types. So the user, adds a page sees this field and if checked to display new header. Is this possible?

leymannx avatar
ne flag
The answer is: yes. I would probably do this with a custom block and then use blockAccess or hook_block_access to hide it given the current node's checkbox value. https://drupal.stackexchange.com/questions/203308/how-can-i-control-block-visibility-with-code
leymannx avatar
ne flag
But you could also do this in hook_preprocess_page where you check if the current route is node canonical, get the node, get the value and set a custom variable you then can if-else in the page template.
mx flag
Thank you, I am complete newbie to Drupal. I cannot change the current header to block, it is directly implemented in page.twig.html. It is new header I can work with.
Score:1
de flag

You can actually access nodes directly from page.html.twig.

It's not as clean as a preprocess approach, but you could do something like this:

{% if node is not empty %}
  {% if node.field_some_field is not empty and node.field_some_field.value == true %}
    {# Output new header #}
  {% endif %}
{% endif %}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.