如何在没有硬编码的情况下将$year, $month变量传递给Twig


Symfony2 How to pass in $year, $month variables to Twig without hardcoding first?

我试图将两个变量传递给Twig,而不首先在控制器中进行硬编码。我在寻找一个简单的解决方案,不要太过分。

现在,根据下面的控制器代码,它显示了我使用的每个月7月的计数,这是我不想要的。

我要做的最终结果是在侧边栏中显示每月的帖子数。

。、6月(3)、7月(5)等

在控制器中,我使用硬编码的年和月并将其传递给Twig。

我怎么能做到这一点,我不需要在控制器中硬编码它,以便它从Twig中获取变量(例如'year': '2014', 'month': 'current month')

我尝试了这个工作,但这是一个可怕的解决方案:

$month1 = $em->getRepository('AcmeDemoBundle:Post')
    ->getPostCountsByMonth('2014', 'June');
$month2 = $em->getRepository('AcmeDemoBundle:Post')
    ->getPostCountsByMonth('2014', 'July');
return $this->render('AcmeDemoBundle:Page:index.html.twig', array(
    'month1' => $month1,
    'month2' => $month2
));

控制器:

$month = $em->getRepository('AcmeDemoBundle:Post')
        ->getPostCountsByMonth('2014', 'July'); <--- what I don't want to do
return $this->render('AcmeDemoBundle:Page:index.html.twig', array(
        'month' => $month,
));

枝:(已尝试以下但不工作:{{ month, { 'year': '2014', 'month': 'July' } }})

July 2014 ({{ month }})

存储库:

public function getPostCountsByMonth($year, $month)
{
    $date = new 'DateTime("{$year}-{$month}-01");
    $toDate = clone $date;
    $toDate->modify("next month midnight -1 second");
    $query = $this->createQueryBuilder('post')
        ->where('post.created BETWEEN :start AND :end')
        ->addOrderBy('post.created', 'DESC')
        ->setParameter('start', $date)
        ->setParameter('end', $toDate);
    $query->select('COUNT(post.created)');
    $month = $query
        ->getQuery()
        ->getSingleScalarResult();
    return $month;
}

一种方法是编写一个分支扩展,这是一个基本的例子,可能会根据您想要做的事情进行优化。

namespace Acme'DemoBundle'Twig;
use Doctrine'ORM'EntityManager
class PostExtension extends 'Twig_Extension
{
    private $em;
    public function __construct(EntityManager $em){
        $this->em  = $em;
    }
    public function getFilters()
    {
        return array(
        );
    }
    public function getFunctions(){
        return array(
            'getPostCount' => new 'Twig_Function_Method($this,'getPostCount')
        );
    }
    public function getPostCount($year,$month)
    {
        return $this->em->getRepository('AcmeDemoBundle:Post')
            ->getPostCountsByMonth($year, '$month');
    }
    public function getName()
    {
        return 'post_extension';
    }
}

基本上你正在创建你自己的树枝过滤器。如果您以前没有这样做过,请查阅文档http://symfony.com/doc/current/cookbook/templating/twig_extension.html

或者就像我在评论中说的,你可以写一个repo函数,按月获取所有计数,然后把它传递给你的模板。

无论哪种方式,都是关于注入你想要的东西。

编辑从小枝过滤器更改为小枝函数。

您还希望将实体管理器作为参数传递到服务中,如下所示:

your_service_name:
            class: Acme'DemoBundle'Twig'PostExtension
            tags:
                - { name: twig.extension }
            arguments:
                em: "@doctrine.orm.entity_manager"