Chayemor Chayemor - 27 days ago 9
Twig Question

Twig add attribute with value in a variable

Using Drupal 8

I want to print out a field's content into the

src
attribute. I have the following template for my view:

<div class="videoWrapperHD">
<iframe width="560" height="315" src="{{ rows[0].content | raw }}"
frameborder="0" allowfullscreen>
</iframe>
</div>


But the iframe gets filled with my own site's "Page Not Found" page instead of the Youtube Video because Twig prints out a whole lot of debug comments before and after printing the variable
rows[0].content
.

Is it possible to disable the debug comments for a specific field? I don't want to have to be disabling/enabling debug to make sure it works as expected.

I also tried using
{{ attributes.setAttribute('src', {{ rows[0].content }} ) }}
, but no dice.

Another failed attempt was:

{% set iframe_src = rows[0].content %}
<div class="videoWrapperHD">
<iframe width="560" height="315" {{ attributes.setAttribute('src', iframe_src) }}
frameborder="0" allowfullscreen></iframe>
</div>


My last idea was this:

{% set url = rows[0].content | raw %}
{% set iframe_src = 'src=' ~ url %}

<div class="videoWrapperHD">
<iframe {{ iframe_src }} ></iframe>
</div>


But it prints out src=Array

Answer

The answer is in another question, I'm pasting it here in case that one gets deleted. The author of the following answer is @4k4

field.content is the rendered field. And in views that means it is no longer a render array, but the finally rendered markup. So this is very problematic to use it as a class name, not only because of twig debug.

Better use the row data, where you find the entity object with the field data from the database. Use clean_class to escape it for using it as a class name:

{{ row._entity.field_myfield.value|clean_class }}