因为在drigal的twig模板中表现得很奇怪

时间:2016-05-16 11:51:08

标签: drupal twig drupal-8

我试图仅显示事件列表中即将发生的事件。以下是我试图展示的方式。

<div class="row">
    {% for item in items %}
        {% if item.content['#node'].field_event_type.getValue()|first.value == 'upcoming' %}
            <div class="col">{{item.content}}</div>
        {% endif %}
    {% endfor %}
</div>

但输出渲染是,第二个事件显示在行div之后,如下所示。我不明白这是怎么回事,因为for循环在行div

<div class="row"> 
  <div class="col"> content </div>
</div><div class="col"> content </div>

预期输出

<div class="row"> 
  <div class="col"> content </div>
  <div class="col"> content </div>
</div>

2 个答案:

答案 0 :(得分:0)

Twig做了很多事情:

  • loading(打开你的Twig内容)
  • 解析(从Twig内容创建一个解析树)
  • 编译(浏览该树以创建php文件)
  • 缓存(将php文件存储在某处以避免下次重新编译)
  • 执行(执行生成的php文件)

在解析期间检测到{% for %}时,Twig会递归调用令牌解析器,直到找到{% endfor %}并构建令牌树。在您的情况下,它看起来像:

root
 |
 --- string
 |
 --- for
 |   |
 |    --- if
 |        |
 |        --- string
 |
 --- string

然后,Twig编译器以递归方式遍历该树并生成相应的php代码。以这种方式,以下Twig循环:

{% for i in 1..5 %}
Value = {{ i }}
{% endfor %}

在PHP中编译:

// line 1
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable(range(1, 5));
foreach ($context['_seq'] as $context["_key"] => $context["i"]) {
    // line 2
    echo "Value = ";
    echo twig_escape_filter($this->env, $context["i"], "html", null, true);
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['i'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;

正如您所看到的,{% for %}只不过是一个简单的foreach,并且由于Twig令牌存储在树中,因此设计无法显示位于一对开放下方的内容/ close标签。

我能看到的唯一可能性是你在Twig中使用的一个标签正在使用输出缓冲,而你在循环中使用的一种方法会破坏ob堆栈(就像一个ob_get_clean()没有任何ob_start(),例如,之前已经打开过。)

我的建议是将你的twig文件名写入你的缓存目录(例如:grep -Ri 'test.twig' cache/),以便查看编译为PHP的文件,准确理解它的作用,然后对其进行调试。

答案 1 :(得分:0)

Instead of filtering your content in twig, filter the results in your Drupal view.

In the "filter criteria" on your view, select the field_event_type field and set it "is equal to" and select/add 'upcoming' as the option.

If you filter in the view, you don't have to mess with the twig template.