【问题标题】:Twig add attribute with value in a variableTwig 在变量中添加具有值的属性
【发布时间】:2016-11-08 18:15:12
【问题描述】:

使用 Drupal 8

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

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

但是 iframe 被我自己网站的“Page Not Found”页面填充,而不是 Youtube 视频,因为 Twig 在打印变量 rows[0].content 之前和之后打印出大量调试 cmets。

是否可以禁用特定字段的调试 cmets?我不想通过禁用/启用调试来确保它按预期工作。

我也尝试使用 {{ 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

【问题讨论】:

    标签: drupal twig drupal-views drupal-8


    【解决方案1】:

    试试这个

    在你的 .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>
    

    【讨论】:

      【解决方案2】:

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

      您还应该确保您的 URL 没有做坏事……如果您只期望 youtube 视频,您应该做一些检查以确保您从内容中获得的内容。

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

      查看 $node,找到值,清理/仔细检查它的值,然后将其设置为 $variables['variable_name'],您应该可以在带有 {{variable_name}} 的 twig 中使用它

      【讨论】:

        【解决方案3】:

        答案在another question,我把它贴在这里,以防万一被删除。以下答案的作者是@4k4

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-07
          • 2011-06-07
          • 1970-01-01
          • 1970-01-01
          • 2014-11-29
          • 2019-08-19
          相关资源
          最近更新 更多