2016-07-07 74 views
0

我有一個數組,我遍歷不同類型的組件拉進我的網頁:傳遞嫩枝變量從陣列到包括

array(
    'content'=> array(
     'componentA'=>array(
      'val'=>'1', 
      'title'=>'sample title' 
     ), 
     'componentB' 
    ) 
) 

我試圖通過從陣列中傳遞變量包含的模板,但我不知道如何將聯接生成的字符串轉換爲包含可以理解爲變量數組的東西。當我從第一個@components包含中排除「with」時,它會打印出我所期望的在可迭代組件中設置的所有默認值,但當我將with屬性放入時,仍會給我一個白色屏幕。我顯示VAR本身,它返回這個字符串: (注意,我也嘗試把引號包圍{{K}}不得要領)

{ val:'1',title:'sample title' } 

如何傳遞變量從我的陣列我零件?

{% for key,item in content %} 
    {% if item is iterable %} 

     {% set var = [] %} 
     {% for k,v in item %} 
      {% set temp %}{% if loop.first %} { {% endif %}{{ k }}:'{{ v }}'{% if loop.last %} } {% endif %}{% endset %} 
      {% set var = var|merge([ temp ]) %} 
     {% endfor %} 
     {% set var = var|join(',') %} 

     {{ include ("@components/" ~ key ~ ".tmpl",var) }} 
    {% else %} 
     {{ include ("@components/" ~ item ~ ".tmpl") }} 
    {% endif %} 
{% endfor %} 

回答

1

您的包含聲明不正確。您正在使用{{ include ... }},應該是{% include ... %}

下面的片段應該工作,如果你只是想從陣列提供的數據(而不是循環數據):

{% for key,item in content %} 
    {% if item is iterable %} 
     {% include ("@components/" ~ key ~ ".tmpl") with item %} 
    {% else %} 
     {% include ("@components/" ~ item ~ ".tmpl") %} 
    {% endif %} 
{% endfor %} 

然後可以使用{{ val }}{{ title }}你的組件模板中。

如果要包括循環的數據,您可以使用:

{% for key,item in content %} 
    {% if item is iterable %} 
     {% include ("@components/" ~ key ~ ".tmpl") with {item: item, loop: loop} %} 
    {% else %} 
     {% include ("@components/" ~ item ~ ".tmpl") %} 
    {% endif %} 
{% endfor %} 

然後你可以在你的組件模板中使用{{ item.val }}{{ item.title }}{{ loop.index }}

+0

工作就像一個魅力,謝謝! –