Symfony, How to generate Asset URL in a Twig Extension class?
symfony, twig
Solution
You can use the templating.helper.assets service directly.
use Symfony\Component\DependencyInjection\ContainerInterface;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
and use it like so:
$this->container->get('templating.helper.assets')->getUrl($iconlink);
Injecting just the templating.helper.assets directly does not work in this case because the twig extension cannot be in the request scope. See the documentation here: https://symfony.com/doc/2.3/cookbook/service_container/scopes.html#using-a-service-from-a-narrower-scope
Problem
I have one class which extends `\Twig_Extension` like below : ``` class MYTwigExtension extends \Twig_Extension { protected $doctrine; protected $router; public function __construct(RegistryInterface $doctrine , $router) { $this->doctrine = $doctrine; $this->router = $router; } public function auth_links($user , $request) { // Some other codes here ... // HOW TO GENERATE $iconlink which is like '/path/to/an/image' $html .= "<img src=\"$iconlink\" alt=\"\" /> "; echo $html; } } ``` My question is How to generate Asset links in a Twig Extension ? I would like a replacement for ASSET helper in my class. Bassically I have no idea what I have to inject or use here ! Thanks in advance. ``` <img src="{{ asset('img/icons/modules/timesheet.png') }}" alt="" /> ```