2015-09-26 42 views
0

我想设置动态变量并获取该变量的值。我已将“orderDetails”传递给我的树枝模板。我想在TWIG中创建动态变量并获取值

$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}}等。给我你的建议。

+0

如果'orderDetails'是一个数组,只需使用'for ... in',不需要生成索引。例如。 '{%for nsOrd in orderDetails%}''。 – Yoshi

+0

'$ customerProfile =阵列( 'NS1'=> $ customerProfile-> getNs1(), 'NS2'=> $ customerProfile-> getNs2(), ) 返回$这 - >渲染('PortalBundle :: popup.html.twig',array( 'orderDetails'=> $ customerProfile ));' –

+0

我如何只提取ns1和ns2? –

回答

0

谢谢Yoshi,我已经在数组中篡改了变量。感谢您的支持,我已经找到并成功使用这个输出。

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