Twig Access Array Index?

我的梦境 提交于 2021-02-06 14:20:38

问题


Is it possible to directly access an array index from within a Twig template?

Here's my setup, using Silex:

return $app['twig']->render('template', array('numbers' => array('one', 'two', 'three')));

so can I do something like this?

{{numbers[0]}}

回答1:


Just before posting this I realized, that's exactly what you can do, but as I didn't find the answer anywhere in the docs or google (correct me if I'm wrong), I've posted this anyway.

{{numbers[0]}} 



回答2:


The answer of Adam, is correct, only to make it clear and improve, you can have access directly to array index

{{ myArray[0] }}

if you need to access in a loop

{% set arrayOfItems = ['ZERO', 'ONE'] %}
{% set myArray = ['APPLE', 'ORANGE'] %}
{% for oneItem in arrayOfItems %}
    <p>{{ oneItem }} equals {{ myArray[loop.index0] }}</p>
{% endfor %}

in this example I used an array inside a non related loop so the result is:

ZERO equals APPLE
ONE equals ORANGE


来源:https://stackoverflow.com/questions/11843880/twig-access-array-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!