【问题标题】:Create and set the value of a twig variable, using index.loop in the variable name使用变量名中的 index.loop 创建和设置 twig 变量的值
【发布时间】:2019-06-17 15:36:07
【问题描述】:

我需要定义一个可以在变量名中包含 index.loop 值的 twig 变量名,以便稍后在另一个循环中调用它。

我想做的是这样的:

{% for x in x.y.z %}
{% set myVar~index.loop = aValue %}
{% endfor %}

以后,我就可以打电话了:

{% if myVar2 == aValue %}
{{ display some stuff }}
{% endif %}

我的问题是我无法找出正确的语法来定义变量 (myVar~index.loop)。

任何建议,不胜感激。

谢谢

【问题讨论】:

  • 连接可以与两个字符串一起使用,也可以与变量一起使用,但不能与两个变量一起使用

标签: symfony drupal twig


【解决方案1】:

这里有两个问题需要解决:

  1. 您需要扩展 twig 才能创建动态变量

  2. 特殊变量_context 不会(直接)发送到循环,而是存储在_context['_parent']


延长树枝

class MyTwigExtension implements \Twig\Extension\ExtensionInterface {
    /**
     * Returns the token parser instances to add to the existing list.
     *
     * @return \Twig\TokenParser\TokenParserInterface[]
     */
    public function getTokenParsers() {
        return [];
    }

    /**
     * Returns the node visitor instances to add to the existing list.
     *
     * @return \Twig\NodeVisitor\NodeVisitorInterface[]
     */
    public function getNodeVisitors() {
        return [];
    }

    /**
     * Returns a list of filters to add to the existing list.
     *
     * @return \Twig\TwigFilter[]
     */
    public function getFilters() {
        return [];
    }

    /**
     * Returns a list of tests to add to the existing list.
     *
     * @return \Twig\TwigTest[]
     */
    public function getTests() {
        return [];
    }

    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return \Twig\TwigFunction[]
     */
    public function getFunctions() {
        return [
            new \Twig\TwigFunction('set', [ $this, 'setValue'], [ 'needs_context' => true,]),
        ];
    }

    /**
     * Returns a list of operators to add to the existing list.
     *
     * @return array<array> First array of unary operators, second array of binary operators
     */
    public function getOperators() {
        return [];
    }

    /**
    * Set reference to $context so you can modify existing values
    * Test if key _parent is set. If true this means the function was called inside a loop
    **/
    public function setValue(&$context, $key, $value) {
        if (isset($context['_parent'])) $context['_parent'][$key] = $value;
        $context[$key] = $value;
    }
}

为树枝添加扩展

$twig->addExtension(new \MyTwigExtension());

现在您可以在模板中使用函数set,例如

{% set foo = 'bar' %}
{% do set('my_var_'~foo, 'foo') %}
{{ my_var_bar }} {# output: foo #}

或在循环内

{% for i in 1..10 %}
    {% do set ('my_var_'~i, i) %}
{% endfor %}

{{ my_var_6 }} {# output: 6 #}

正如我所说,特殊变量_context 不会直接发送到函数,即使needs_context 设置为true。 Twig_context 的当前内容复制到 _parent 中,以便循环获得它自己的私有变量范围,并且您不能覆盖 _context 中的任何原始值

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多