我想在TWIG中生成动态变量并获取值

我想在TWIG中生成动态变量并获取值,twig,Twig,我想设置动态变量并获取该变量的值。我已将“orderDetails”传递到我的小树枝模板 $customerProfile = array( 'ns1' => $customerProfile->getNs1(), 'ns2' => $customerProfile->getNs2(), 'custId' => $customerProfile->getCustId() ) return $this->ren

我想设置动态变量并获取该变量的值。我已将“orderDetails”传递到我的小树枝模板

    $customerProfile = array(
      'ns1' => $customerProfile->getNs1(),
      'ns2' => $customerProfile->getNs2(),
      'custId' => $customerProfile->getCustId()
)

return $this->render('PortalBundle::popup.html.twig', array(
            'orderDetails' => $customerProfile
        ));
获取像{orderDetails.ns1}},{{orderDetails.ns2}}这样的变量,但是我有15到16个像这样的变量,我想在循环中获取这个变量

我有这样的代码

{% for i in 1..13 %}
     {% set nsOrd = 'orderDetails.ns'~i %}
          {% if nsOrd %}
                {{nsOrd}}
          {% endif %}
{% endfor %}

我想获取变量{{orderDetails.ns1}}和其他变量。给我你的建议。

谢谢Yoshi,我已经在数组中添加了数百个变量。感谢您的支持,我已经找到并成功地获得了使用此工具的输出

{% for i in 1..13 %}
     {% if orderDetails['ns' ~ i] is defined %}
           {{orderDetails['ns' ~ i]}}
     {% endif %}
{% endfor %}

如果
orderDetails
是一个数组,只需在
中为…使用
,无需生成索引。例如,
{%for orderDetails%}
$customerProfile=array('ns1'=>$customerProfile->getNs1(),'ns2'=>$customerProfile->getNs2(),)返回$this->render('PortalBundle::popup.html.twig',array('orderDetails'=>$customerProfile))如何仅获取ns1和ns2?我明白了。好的,您可以简单地在['ns1',ns2]}中为x执行
{%。但老实说,我认为你的观点太过分了。只需在控制器中创建一个好的、可用的数据结构,并将其传递给视图。