Symfony2如何建立新的Extension(在模板中使用json_decode)

Thats easy if you extend twig.


First, create a class that will contain the extension:

<?php
 
namespace Acme\DemoBundle\Twig\Extension;
 
use Symfony\Component\DependencyInjection\ContainerInterface;  
use \Twig_Extension;
 
class VarsExtension extends Twig_Extension
{
    protected $container;
 
    public function __construct(ContainerInterface $container) 
    {
        $this->container = $container;
    }
 
    public function getName() 
    {
        return 'some.extension';
    }
 
    public function getFilters() {
        return array(
            'json_decode'   => new \Twig_Filter_Method($this, 'jsonDecode'),
        );
    }
 
    public function jsonDecode($str) {
        return json_decode($str);
    }
}



Then, register that class in your Services.xml file:

<service id="some_id" class="Acme\DemoBundle\Twig\Extension\VarsExtension">
        <tag name="twig.extension" />
        <argument type="service" id="service_container" />
</service>

or yml:

services:
    jy.admin.twig.extension:
        class: Jy\AdminBundle\Twig\JsonExtension
        tags:
             - { name: twig.extension }
        arguments: [ @service_container ]


Then, use it on your twig templates:


{% set obj = form_label(category) | json_decode %}


by 雪洁 2014-12-10 12:09:32 2274 views
我来说几句

相关文章