Подтвердить что ты не робот

Как создать фильтр сглаживания symfony?

Например, мое пространство имен пакетов - это Facebook\Bundle\FacebookBundle\Extension.

Используя это, как я могу создать расширение ветки?

4b9b3361

Ответ 1

Вы также можете создавать функции твига с помощью функции getFunctions()

class FacebookExtension extends Twig_Extension
{
    public function getFunctions()
    {
        return array(
            'myFunction' => new Twig_Filter_Method($this, 'myFunction'),
        );
    }

    public function myFunction($arg1)
    {
        return $arg1;
    }

Используйте свою функцию следующим образом:

{{ myFunction('my_param') }}

Ответ 2

Все это здесь: Как написать пользовательское расширение Twig.

1. Создайте расширение:

// src/Facebook/Bundle/Twig/FacebookExtension.php
namespace Facebook\Bundle\Twig;

use Twig_Extension;
use Twig_Filter_Method;

class FacebookExtension extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            'myfilter' => new Twig_Filter_Method($this, 'myFilter'),
        );
    }

    public function myFilter($arg1, $arg2='')
    {
        return sprintf('something %s %s', $arg1, $arg2);
    }

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

2. Зарегистрировать расширение как услугу

# src/Facebook/Bundle/Resources/config/services.yml
services:
    facebook.twig.facebook_extension:
        class: Facebook\Bundle\Twig\AcmeExtension
        tags:
            - { name: twig.extension }

3. Используйте его

{{ 'blah'|myfilter('somearg') }}

Ответ 3

Класс Twig_Filter_Method DEPRECATED, поскольку Symfony 2.1

Вместо этого используйте класс Twig_SimpleFilter, как показано в следующем примере:

\SRC\Acme\Bundle\CoreBundle\Twig\DatetimeExtension.php

<?php

namespace Acme\Bundle\CoreBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;

class DatetimeExtension extends \Twig_Extension
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getFilters()
    {
        return array(
            'dateFormat' => new \Twig_SimpleFilter('dateFormat', array($this, 'dateFormat')),
            'datetimeFormat' => new \Twig_SimpleFilter('datetimeFormat', array($this, 'datetimeFormat'))
        );
    }

    /**
     * @param mixed $date
     * @return string
     */
    public function dateFormat($date)
    {
        $format = $this->container->getParameter('acme_core.date_format');
        return $this->format($date, $format);
    }

    /**
     * @param mixed $date
     * @return string
     */
    public function datetimeFormat($date)
    {
        $format = $this->container->getParameter('acme_core.datetime_format');
        return $this->format($date, $format);
    }

    /**
     * @param mixed $date
     * @param string $format
     * @throws \Twig_Error
     * @return string
     */
    private function format($date, $format)
    {
        if (is_int($date) || (is_string($date) && preg_match('/^[0-9]+$/iu', $date))) {
            return date($format, intval($date, 10));
        } else if (is_string($date) && !preg_match('/^[0-9]+$/', $date)) {
            return date($format, strtotime($date));
        } else if ($date instanceof \DateTime) {
            return $date->format($format);
        } else {
            throw new \Twig_Error('Date or datetime parameter not valid');
        }
    }

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

\SRC\Acme\Bundle\CoreBundle\Resources\Config\services.yml

services:
    acme_core.twig.datetime_extension:
        class: Acme\Bundle\CoreBundle\Twig\DatetimeExtension
        arguments: [@service_container]
        tags:
            - { name: twig.extension }

Пример использования:

{{ value|datetimeFormat }}

Документация по Symfony: http://symfony.com/doc/master/cookbook/templating/twig_extension.html

Документация Twig: http://twig.sensiolabs.org/doc/advanced.html#id3