I have a boolean field within my Page content type called Hide Title.

I need to conditionally add a class to h1's to visually hide them if this field is checked.

I have the following within page-title.html.twig

{% set hide_title = content.field_hide_title.0 %}

{% if 'On' in hide_title %}
    <h1 {{ title_attributes.addClass('visually-hidden') }}>{{ title }}</h1>
{% else %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}

This is is not adding the class while the boolean is set on or off.

  • Add {{ hide_title }} right after you set it, as a cheap way of finding out what the value you're getting is. – beltouche Mar 22 at 21:40
  • @beltouche Good idea – it's not returning anything, hmm. Tried changing to node.field_hide_title.0 but still nothing. – 4oh3 Mar 22 at 21:50
  • I recommend turning on twig debugging and using dev to dig into the field so you can find what you're looking for. See drupal.org/docs/8/theming/twig/debugging-twig-templates – beltouche Mar 22 at 21:53

In page-title.html.twig you don't have access to content variable.
according to page-title.html.twig comment section:

Available variables are:

  • title_attributes
  • title_prefix
  • title
  • title_suffix

So you should implement hook_preprocess_HOOK to passe hide_title to your twig like the following:

 * Implements hook_preprocess_HOOK().
function MYMODULE_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['hide_title'] = $node->field_hide_title->value;

Now you can do the following in your twig:

{% if hide_title == "1" %}
    <h1 {{ title_attributes.addClass('visually-hidden') }}>{{ title }}</h1>
  {% else %}
    <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
  • Now that makes sense, thanks so much! – 4oh3 Mar 23 at 1:10
  • You are welcome, glad that helped! – berramou Mar 23 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.