0

I am using the following code to set a variable "tab1visibility" from the twig tweak value for field_hidden based on a block id. {% set tab1visibility = drupal_field('field_hidden', 'block_content', 7) %}

This works perfectly but returns the value with the expected markup.

When I try to use |striptags on this newly created value it returns nothing.

So

{% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

<p>{{tab1visibility}}</p>

returns true or false wrapped in my typical field div templating.

{% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

<p>{{tab1visibility|striptags}}</p>

returns nothing no markup or the raw value.

How do I get just the value without the surrounding markup?

2

A field formatter stores the field object inside of the render array for reference later, so that you can still access the raw values:

{% set field = drupal_field('field_example', 'block_content', 1) %}
{% set value = field['#items'].0.value %}
{{ value }}

This is the same for all field formatters.


Your approach might also work, if you |render the field first and then apply |striptags:

{{ tab1visibility|render|striptags }}

But not in a consistent way, because it depends on the specific field type and the configured field formatter.

  • The first option was exactly what I was looking for thanks @4k4 ! – Shawn Matthews Mar 18 at 20:01
1

I suppose the markup comes from field.html.twig template. You can override that template for this field in your theme. Another approach is to turn off the theming like follows.

{{ drupal_field('field_hidden', 'block_content', 7)|without('#theme') }}

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.