Twig 在变量中添加具有值的属性

Twig add attribute with value in a variable

使用 Drupal 8

我想将字段的内容打印到 src 属性中。我的视图有以下模板:

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

但是 iframe 充满了我自己网站的“找不到页面”页面,而不是 Youtube 视频,因为 Twig 在打印变量 rows[0].content

是否可以禁用特定字段的调试注释?我不想 disabling/enabling 调试以确保它按预期工作。

我也试过使用 {{ attributes.setAttribute('src', {{ rows[0].content }} ) }} ,但没有骰子。

另一个失败的尝试是:

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

我最后的想法是:

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

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

但是它打印出 src=Array

听起来像是必须在预处理器中完成的事情。如果你从节点对象而不是内容数组中获取它,它不应该得到所有调试废话。

您还应确保您的 URL 没有做坏事...如果您只希望观看 YouTube 视频,则应进行一些检查以确保您从内容中获得的是该视频。

https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/template_preprocess_node/8.2.x

查看 $node,找到值,sanitize/double 检查它的值,然后将它设置为 $variables['variable_name'] 你应该可以在 twig 中使用它 {{variable_name}}

试试这个

在你的.theme

function your_theme_preprocess_field(&$variables, $hook) {
    switch ($variables['element']['#field_name']) {
        case 'field_iframe_src':
            $variables['iframe_src'] = $variables['items'][0]['content']['#context']['value'];
            break;
    }
}

在你的树枝上

   <iframe width="560" height="315" src="{{ iframe_src|raw}}" 
      frameborder="0" allowfullscreen>
     </iframe>

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

field.content是渲染的字段。在视图中,这意味着它不再是渲染数组,而是最终渲染的标记。所以将它用作 class 名称是非常有问题的,不仅仅是因为 twig debug。

最好使用行数据,在这里您可以从数据库中找到带有字段数据的实体对象。使用 clean_class 对其进行转义以将其用作 class 名称:

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