2013-09-21 44 views
5

我對樹枝有點新,我知道有可能在模板中添加值並將它們收集在一個變量中。但是我真正需要的是在總結它們之前在模板中顯示總結值。我需要像舊的symfony中的插槽。或者在PHP中,我可以通過ob_start()來做到這一點。不知何故,它可能在樹枝上?樹枝總和行以上

我喜歡這樣的東西。

sum is: {{ sum }} {# obviously it is 0 right here, but i want the value from the calculation #} 

{# some content.. #} 

{% set sum = 0 %} 

{% for r in a.numbers} 

    {% set sum = sum + r.number %} 

{% endfor %} 
+1

你爲什麼不在控制器中進行計算? Twig實際上只是假設用於顯示計算的數據。在MVC中,你的觀點並不是真的假設正在運行計算。 – Chausser

回答

2

一個可能的解決方案是使用MVC標準,讓你的控制器爲你做總和計算。

//In your controller file 

public function yourControllerAction(){ 
    //how ever you define $a and $content would go here 

    $sum = 0; 
    foreach($objects as $a) 
     $sum = 0; 
     foreach($a->numbers as $r){ 
      $sum += $r->number; 
     } 
     $a->sum = $sum; 
    } 


    return array(
     'objects' => $objects, 
     'content' => $content 
    ); 
} 

現在你有總和變量已經計算在樹枝文件中使用:

{# twig file #} 
{% for a in objects %} 
    sum is: {{ a.sum }} 
    {% for number in a.numbers %} 
     {{number}} 
    {% endfor %} 
{% endfor %} 
{# some content.. #} 
+0

我將一個對象數組傳遞給包含數字的模板。例如: 數組(0 => Object1,1 => Object2)等。這些對象包含某些集合中的數字。我想如果我可以將模板中的數字加起來,那麼我不需要用像4個foreach這樣的複雜邏輯來處理這個對象數組。 這對我來說簡單些,但是我可能會根據你的建議去處理這些數字。 感謝您的答案! – omgitsdrobinoha

+0

當我開始實施你的答案時,我的腦海中浮現出一些東西。我需要將這些數據按對象分組,這樣當我列出對象時,我可以輕鬆處理對象的總和。 我有點像這樣的:$ obj-> numbers是一個數組,我列出和$ obj-> sum可以是總結值。 – omgitsdrobinoha

+0

我已經更新了我的答案,根據您的對象結構給出了一個示例。如果你添加一個sum屬性到你的對象,那麼你可以使用上面的方法來設置它。那麼你的樹枝實現看起來就像我在那裏一樣。 – Chausser

3

如果你不想使用控制器和wan噸至做樹枝求和,然後嘗試使用set命令:

{# do loop first and assign whatever output you want to a variable #} 
{% set sum = 0 %}  
{% set loopOutput %}    
    {% for r in a.numbers}    
     {% set sum = sum + r.number %}   
    {% endfor %}  
{% endset %} 

sum is: {{ sum }} 

{# some content.. #} 

{{ loopOutput }} 

我假定環是在一個特定的地方,因爲它的目的是輸出的東西到模板,這可以讓你重新加載順序,而仍然顯示你想要的。

0

我建立一個樹枝延伸來實現這一點。目標是給數組和屬性一個樹枝擴展並計算結果。

首先,註冊服務:

affiliate_dashboard.twig.propertysum: 
    class: AffiliateDashboardBundle\Service\PropertySum 
    public: false 
    tags: 
     - { name: twig.extension } 

然後實現TwigExtension:

命名空間AffiliateDashboardBundle \服務;

class PropertySum extends \Twig_Extension 
{ 
    public function getFilters() 
    { 
     return array(
      new \Twig_SimpleFilter('propertySum', array($this, 'propertySum')), 
     ); 
    } 

    public function propertySum($collection, $property) 
    { 
     $sum = 0; 
     $method = 'get' . ucfirst($property); 

     foreach ($collection as $item) { 
      if (method_exists($item, $method)) { 
       $sum += call_user_func(array($item, $method)); 
      } 
     } 

     return $sum; 
    } 

    public function getName() 
    { 
     return 'property_sum'; 
    } 
} 

之後,您可以輕鬆地計算特定集合的屬性之和。還與教條關係合作。用法示例:

{{ blogpost.affiliateTag.sales|propertySum('revenue') }} 

完成!