T
T
Tarakkolya2014-09-01 22:22:36
PHP
Tarakkolya, 2014-09-01 22:22:36

How to create twig extension correctly?

I tried to pull the entities using the twig extension, but it doesn't work.
service class:

<?php

namespace NT\MainBundle\Twig\Extension;

use Doctrine\Common\Persistence\ObjectManager;

class ShopExtension extends \Twig_Extension
{
    protected $em;

    public function __construct(ObjectManager $em)
    {
        $this->em = $em;
    }

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

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('get_shops', array($this, 'getShops'))
        );
    }

    public function getShops()
    {
        return $this->em->getRepository('NTMainBundle:Shop')->findAll();
    }
}

services.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <parameters>
        <parameter key="shop.class">NT\MainBundle\Twig\Extension\ShopExtension</parameter>
    </parameters>
    <services>
        <service id="twig.extension.nt.main_bundle.shop_extension" class="%shop.class%">
            <argument type="service" id="doctrine.orm.entity_manager"/>
        </service>
    </services>
</container>

when called get_shops()in a template, returns
The function "get_shops" does not exist in ::base.html.twig

what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergej, 2014-09-01
@Tarakkolya

I do like this:

class TwigExtension extends \Twig_Extension 
{
 // ......
 public function getFunctions() {
    return  [
        'functionName' => new \Twig_Function_Method($this, 'functionName'), 
                      // ....
     ];
}
 // .....
}

front.yourbundle.extension.twig:
        class: Front\YourBundle\Extension\TwigExtension
        arguments:
            doctrine: "@doctrine.orm.entity_manager"
        tags:
            - { name: twig.extension }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question