在树枝过滤器上静态调用

时间:2015-04-14 13:29:58

标签: symfony filter twig

我试图获得一个可以按分数对实体进行排序的树枝过滤器。我的City类得到了getter和setter的得分属性,我创建了这个扩展名:

<?php

namespace AOFVH\HomepageBundle\Twig;
use Twig_Extension, Twig_SimpleFilter, Twig_Environment;

class ScoreExtension extends \Twig_Extension
{
public function getFilters()
{
    return array(
        $filter = new Twig_SimpleFilter('score', array('AOFVH\FlyBundle\Entity\City', 'getScore'))
    );
}

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

我称之为:

        {% for cit in cities|score %}
      <a href="{{ path('aofvh_city', {'name': cit.name}) }}">
        <div class="col-lg-4 col-md-12" style="margin-bottom:10px;">
        <img src="{{ asset('Cities/'~cit.name~'.png') }}" class="img" alt="Cinque Terre" width="300" height="300">
        <h2>{{cit.name}}</h2>
        </div>
      </a>

        {% endfor %}

但由于某种原因,我无法渲染它,而是我引发了这个错误

 ContextErrorException: Runtime Notice: call_user_func_array() expects parameter 1 to be a valid callback, non-static method AOFVH\FlyBundle\Entity\City::getScore() should not be called statically 

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

Twig_SimpleFilter的构造函数的第二个参数需要callable

如果您传递类名和方法名,它将静态调用该类的方法:

array('SomeClass', 'someMethod')

如果你传给它一个类和方法名的实例,它将在对象中调用该方法:

array($this->someInstance, 'someMethod')

这意味着您要么getScore()静态,要么创建City的实例并使用它(可能使用依赖注入获取它)。

答案 1 :(得分:0)

你必须做这样的事情,使用过滤的实际变量。在这里,我猜cities是一个集合:

class ScoreExtension extends \Twig_Extension
{

    public function getFilters()
    {
        return array(
            $filter = new Twig_SimpleFilter('score', array($this, 'getCityScore'))
        );
    }

    public function getCityScore($cities)
    {
        $scores = array();

        foreach ($cities as $city) {
            $scores[] = $city->getScore();
        }

        return $scores;
    }

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

}