2017-01-12 69 views
1

我已經將導航菜單的渲染設置爲單獨的樹枝模板。原因是菜單是在應用程序的兩個不同位置生成的。將樹枝中的變量傳遞給包含的模板

現在我想給一個導航菜單的參數,所以我知道從它產生的地方是這些一些小的差異。

我試着下面的代碼,但變量沒有在導航菜單模板知道:

{% set menuType = 'user' %} 
{% include 'MyBundle:nav.html.twig' with menuType %} 

也試過:

{% include 'MyBundle:nav.html.twig' with {'menuType': 'user'} %} 

在這兩種情況下,樹枝產生的錯誤{{menuType} }不存在?

回答

1

令人驚訝的是,雖然我認爲有可能像你一樣傳遞一個簡單的變量,但它只顯示數組被接受爲傳遞值。 (雖然include doc的兩個例子是數組,這不是專門一種高精度。)

你的情況,你必須把它這樣寫:

{% set menuType = 'user' %} 
{% include 'MyBundle:nav.html.twig' with {menuType:menuType} only %} 

注意:我添加關鍵字only禁止訪問上下文。 沒有它,你不需要將變量傳遞給包含的模板,因爲它們可以訪問它們。 (這是禁用它一個很好的做法。)

這裏是一個Twigfiddle一些測試和轉儲:https://twigfiddle.com/gtnqvv

{% set menuType = 'user' %} 
{% set vars = {'foo': 'bar'} %} 
{% set z = 'bob' %} 

{# vars dumps ommitted here, see the fiddle. #} 

{#% include '1.html.twig' with menuType only %#} 
{% include '1.html.twig' with {menuType:menuType} only %} 
{% include '2.html.twig' with vars only %} 
{% include '3.html.twig' with {z:z} only %} 
{#% include '3.html.twig' with z only %#} 

第一和最後一個註釋行不行,你也知道,這裏是錯誤:

Uncaught TypeError: Argument 1 passed to Twig_Template::display() must be of the type array, string given

,只要你想的第二部作品,你就必須做一個數組。 (無論如何都是奇怪的)

第三行是來自Twig doc的測試,第四行是使用另一個變量名稱進行的測試,可以肯定。

0

我在我的代碼中使用它,它適用於我。該變種foobaz.html.twig直接使用:

{% set foo = 'foo' %} 
{{ include ('MyBundle:bar:baz.html.twig') }} 

在樹枝文檔,它說:

Included templates have access to the variables of the active context. [...] The context is passed by default to the template but you can also pass additional variables

+0

注意這是一個很好的做法也禁止訪問上下文中有'only'關鍵字。 – Veve

+0

@Veve,爲什麼這應該是好的做法? – DarkBee

0

我創建了一個樣本twigfiddle爲你在這裏:

https://twigfiddle.com/fpzv26

你需要的東西像這樣:

{% set vars = { 'menuType' : 'user'} %} 
{% include 'MyBundle:nav.html.twig' with vars %} 
+0

在twigfiddle中,我不得不縮短模板文件名稱的長度。我抱怨21個字符的限制,所以我用「nav.html.twig」。 –

+0

它不允許傳遞不是像@ Tom's menuType這樣的數組的變量。 – Veve

+0

Right @Veve,我看到了你的帖子。其實當我做了我的傻瓜我也注意到了。我認爲OP的原始帖子也應該起作用,這就是爲什麼我去twigfiddle。我找到了和你一樣的東西。它需要是一個數組。希望OP能夠理解這一點。 –

0

只要變量可用或包含在父模板中,它就可用於任何包含的或子模板。

例: 控制器:

return $this->render('CmsBundle:EmailBulk:edit.html.twig', array(
      'entity' => $entity, 
      'form' => $editForm->createView(), 
      'tokens' => $tokens 
     )); 

然後,edit.html.twig:

{% block body -%} 
    <div class="panel panel-default animated fadeIn delay-400"> 
     <div class="panel-heading"> 
      blah blah blah 
     </div> 
     <div class="panel-body"> 
      {{ include('CmsBundle:EmailBulk:form.html.twig') }} 
     </div> 
    </div> 
{% endblock %} 

來自控制器的 '形式' 變量是提供給包括模板form.html.twig

+0

這從控制器工作。但是,當我在父樹枝中定義一個新變量{%set menuType ='user'%}時,它不會傳遞給子樹枝。 – Tom

相關問題