0

I created a new field for a custom block type and have already exported necessary yml files and updated the yml for different view modes.

However, when I make a reference to the new field using the correct field_machine_name, it doesn't recognize it.

This new field is a checkbox, that when enabled, hides the h1 header of the page, but is still visible for screen readers.

sample code:

{% set hide_header_title = content.field_hide_header_title|render|striptags|trim %}

 {% if hide_header_title == 1 %}
    {% set hide_header_title = "show-for-sr" %}
  {% else %}
    {% set hide_header_title = "block" %}
  {% endif %}

With the code above, I'm only getting to the else statement.

  • try {% if hide_header_title === 1 %} – Mech Jun 20 at 23:20
  • Try getting the raw value this way, hide_header_title = content.field_hide_header_title.0 – No Sssweat Jun 21 at 5:23
  • If my previous comment doesn't work, you might also want to check by printing it {{ hide_header_title }} just to make sure it's indeed giving a 1 or 0. – No Sssweat Jun 21 at 5:25
  • @kcstring, {{ content.field_example }} does render the field as asked in the question title, but it does not reference it. For this you need the block content object, see drupal.stackexchange.com/a/212711/47547 – 4k4 Jun 21 at 7:22
  • @Mech, thank you for your suggestion, but it gave me this error: "The website encountered an unexpected error. Please try again later.". Turns out it was giving me either "On" or "Off". – kcsting Jun 22 at 13:54
0

@4k4, thanks for sharing the link. I was able to retrieve the value this way: content.field_hide_header_title[0]

content.field_myfield[0] still gets the rendered output, now of the first field item. It's not a good idea to use it for programming, because the output can be formatted in different ways and is translatable. You don't want to adjust the code anytime this is changing.

For programming if/else code better use the block content object.

content['#block_content'].field_myfield.value

This is a similar question for a node field: Boolean field inside node twig renders ok but does not work in if statement

| improve this answer | |

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.