Setting element of array from Twig

前端 未结 10 776
北恋
北恋 2020-12-04 09:55

How can I set member of an already existing array from Twig?

I tried doing it next way:

{% set arr[\'element\'] = \'value\' %}

but

10条回答
  •  旧巷少年郎
    2020-12-04 10:20

    I've found this issue very annoying, and my solution is perhaps orthodox and not inline with the Twig philosophy, but I developed the following:

    $function = new Twig_Function('set_element', function ($data, $key, $value) {
        // Assign value to $data[$key]
        if (!is_array($data)) {
            return $data;
        }
        $data[$key] = $value;
        return $data;
    });
    $twig->addFunction($function);
    

    that can be used as follows:

    {% set arr = set_element(arr, 'element', 'value') %}

提交回复
热议问题