Answer the question
In order to leave comments, you need to log in
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();
}
}
<?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>
get_shops()
in a template, returnsThe function "get_shops" does not exist in ::base.html.twig
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question