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 }