【问题标题】:TWIG - include variables in different templateTWIG - 在不同的模板中包含变量
【发布时间】:2020-10-22 14:25:12
【问题描述】:

我想在不同的模板中包含相同的变量

vars_catchphrase.twig

{% set catchphrase_size = '' %}
{% if var.tile_catchphrase|length <= 4 %}
    {% set catchphrase_size = 'size-lg' %}
{% elseif var.tile_catchphrase|length >= 5 and var.tile_catchphrase|length <= 8 %}
    {% set catchphrase_size = 'size-md' %}
{% elseif var.tile_catchphrase|length >= 9 and var.tile_catchphrase|length <= 12 %}
    {% set catchphrase_size = 'size-sm' %}
{% elseif var.tile_catchphrase|length >= 13 %}
    {% set catchphrase_size = 'size-xs' %}
{% endif %}

我尝试将其包含在内(因为上下文有时不同):

{% include 'vars_catchphrase.twig' with { 'var' : post } %}

当上下文与 post 不同时,我使用另一个:

{% include 'vars_catchphrase.twig' with { 'var' : item } %} 

example.twig

{% for item in list %}
    {% include 'vars_catchphrase.twig' with { 'var' : item } %}

    <p class="catchphrase {{ catchphrase_size }}">{{ item.title }}</p>
{% endfor %}

变量为空。请问我可以帮忙吗?

【问题讨论】:

  • 也许 'var' 变量是一个数组,而不是一个对象。
  • var["tile_catchphrase"] insetad of var.tile_catchphrase
  • @danielarend 没关系

标签: twig


【解决方案1】:

您包含的模板有自己的变量范围,这意味着在此模板中定义的变量不会被模板知道。这就是说,包含的模板也不能改变父级的上下文(默认情况下),这是因为twig 通过值而不是引用传递上下文数组。

foo.twig

{% set foo = 'foo' %}
{% include 'bar.twig' %}
{{ foo }}

bar.twig

{% set foo = 'bar' %}

上面的example仍然会输出foo


为了解决您的问题,我建议在twig 中添加自定义过滤器

<?php
    $twig->addFilter(new \Twig\TwigFilter('catchphrase_size', function($value) {
        switch(true) {
            case strlen($value->tile_catchphrase) >= 13: return 'size-xs';
            case strlen($value->tile_catchphrase) >= 9: return 'size-sm';
            case strlen($value->tile_catchphrase) >= 5: return 'size-md';
            default: return 'size-lg';
        }
    });

这样你就可以在任何地方使用过滤器,

{% for item in list %}
    <p class="catchphrase {{ item|catchphrase_size }}">{{ item.title }}</p>
{% endfor %}

【讨论】:

  • 这是最好的清洁解决方案!我在 TWIG 方面还有很多进展。再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2012-12-25
  • 2018-04-06
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
相关资源
最近更新 更多