Symfony,如何在Twig Extension类中生成资产URL?

PMo*_*bed 4 symfony twig

我有一个类\Twig_Extension如下所示:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在Twig扩展中生成资产链接?我想在班上替换ASSET助手.我不知道我要注射或使用的是什么!提前致谢.

 <img src="{{ asset('img/icons/modules/timesheet.png') }}" alt="" /> 
Run Code Online (Sandbox Code Playgroud)

MDr*_*tte 17

您可以直接使用templating.helper.assets服务.

use Symfony\Component\DependencyInjection\ContainerInterface;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

$this->container->get('templating.helper.assets')->getUrl($iconlink);
Run Code Online (Sandbox Code Playgroud)

直接注入templating.helper.assets在这种情况下不起作用,因为twig扩展不能在请求范围内.请参阅此处的文档:http://symfony.com/doc/current/cookbook/service_container/scopes.html#using-a-service-from-a-narrower-scope


J. *_*uni 6

我不想处理依赖注入容器.这就是我做的:

use Twig_Environment as Environment;

class MyTwigExtension extends \Twig_Extension
{
    protected $twig;
    protected $assetFunction;

    public function initRuntime(Environment $twig)
    {
        $this->twig = $twig;
    }

    protected function asset($asset)
    {
        if (empty($this->assetFunction)) {
             $this->assetFunction = $this->twig->getFunction('asset')->getCallable();
        }
        return call_user_func($this->assetFunction, $asset);
    }
Run Code Online (Sandbox Code Playgroud)

我查看了Twig_Extension类代码,并在initRuntime那里找到了这个方法,在我们的自定义Extension类中被覆盖.它收到了Twig_Environment作为参数!该对象有一个getFunction返回Twig_Function实例的方法.我们只需要传递函数名称(asset在我们的例子中).

Twig_Function对象有一个getCallable方法,所以我们最终可以有一个可调用的asset函数.

我已经asset为我自己的扩展类创建了一个方法.在其他任何地方,我可以简单地调用$this->asset()并获得与{{ asset() }}模板中相同的结果.

编辑:清除缓存时,getFunction调用initRuntime会抛出范围异常.所以我把它移到了自定义asset方法.它工作正常.

  • 这次真是万分感谢.我更喜欢这种方法而不是注入容器 (3认同)
  • 这将触发现在的弃用警告,可以通过实现`Twig_Extension_InitRuntimeInterface`或通过注入`Twig_Environment`重新编写代码来修复:http://twig.sensiolabs.org/doc/advanced.html#environment-aware-filters (2认同)