2013-09-21 46 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') }} 

完成!