查找树枝数组中非保护值是否为空


Find if twig array is empty of non-protected values

给定一个php数组在twig模板中:

object(Drupal'Core'Template'Attribute)#1208 (1) {
    ["storage":protected]=> array(0) { }
}

如何检查数组中是否没有非保护元素?这个想法是,我只能操作非受保护的值,所以如果只有受保护的值存在,我可以假装数组是空的。

到目前为止,我的支票如下:
{% if attributes is defined and attributes is not empty %}
    <div{{ attributes }}>
      {{ content }}
    </div>
{% else %}
    {{ content }}
{% endif %}

以当前形式显示<div>[Content]</div>。相反,我想看到:[Content]

帮忙吗?

如果这是在Drupal 8中,您可以通过渲染传递属性值来查找,如下所示:

{% if attributes|render %}
  <div{{ attributes }}>
    {{ content }}
  </div>
{% else %}
  {{ content }}
{% endif %}
  1. 扩展树枝

    <?php
       $twig = new Twig_Environment($loader);
       $twig->addFilter(new Twig_SimpleFilter('accessible_properties', 'get_object_vars'));
    
  2. 在模板内使用

    {% set public_attributes = attributes is defined ? (attributes|accessible_properties) : [] %}
    {% if public_attributes is not empty %}
        ...
    {% else %}
        ...
    {% endif %}