Symfony Twig 扩展基本示例

在这个例子中我定义了两个自定义函数。1 - countryFilter 函数获取国家/地区短代码作为输入并返回国家/地区全名。2 - _countPrinterTasks 用于计算分配给特定用户的任务的数量。

<?php

namespace DashboardBundle\Twig\Extension;

use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContext;

/**
 * Class DashboardExtension
 * @package DashboardBundle\Twig\Extension
 */
class DashboardExtension extends \Twig_Extension
{
    protected $doctrine;
    private $context;
   

    /**
     * DashboardExtension constructor.
     * @param RegistryInterface $doctrine
     * @param SecurityContext $context
     */
    public function __construct(RegistryInterface $doctrine,SecurityContext $context)
    {
        $this->doctrine = $doctrine;
        $this->context = $context;
    }

    /**
     * @return mixed
     */
    public function getUser()
    {
        return $this->context->getToken()->getUser();
    }

    /**
     * @return array
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('country', array($this, 'countryFilter')),
            new \Twig_SimpleFilter('count_printer_tasks', array($this, '_countPrinterTasks')),
        );
    }

 /**
     * @param $countryCode
     * @param string $locale
     * @return mixed
     */
    public function countryFilter($countryCode,$locale = "en")
    {
        $c = \Symfony\Component\Intl\Intl::getRegionBundle()->getCountryNames($locale);

        return array_key_exists($countryCode, $c)
            ? $c[$countryCode]
            : $countryCode;
    }

    /**
     * Returns total count of printer's tasks.
     * @return mixed
     */
    public function _countPrinterTasks(){
        $count = $this->doctrine->getRepository('DashboardBundle:Task')->countPrinterTasks($this->getUser());
        return $count;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'app_extension';
    }
}

要从 Twig 调用它,我们只需要使用如下;

{% set printer_tasks = 0|count_printer_tasks() %}

 <tr>
    <td>Nationality</td>
    <td>
        {{ user.getnationality|country|ucwords }}
    </td>
</tr>

并将此扩展声明为 bundle/resource/config/service.yml 文件中的服务。

services:

    app.twig_extension:
        class: DashboardBundle\Twig\Extension\DashboardExtension
        arguments: ["@doctrine", @security.context]
        tags:
            - { name: twig.extension }