使用Symfony2在Twig Extension中包含资产 [英] Include assets in Twig Extension with Symfony2
问题描述
我想在Twig扩展名中包含资产和一些脚本文件.例如.我想声明树枝函数{{ init_project() }}
,但是当我在树枝函数'<script type="text/javascript" src="{{ asset('bundles/mybundle/js/script.js') }}"></script>'
中编写代码时,它不起作用,它在浏览器的调试面板中返回404错误.那我该怎么做呢?
I want to include asset with some script file in Twig extension. E.g. I want to declare twig function {{ init_project() }}
, but when I writing in my twig function '<script type="text/javascript" src="{{ asset('bundles/mybundle/js/script.js') }}"></script>'
, it dont work, it return 404 error in debug panel of browser. So how I can do this?
推荐答案
查看'asset'
树枝函数:
Look at the 'asset'
twig function :
您可以在\Symfony\Bundle\TwigBundle\Extensions\AssetsExtension
public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null)
{
$url = $this->container->get('templating.helper.assets')->getUrl($path, $packageName, $version);
if (!$absolute) {
return $url;
}
return $this->ensureUrlIsAbsolute($url);
}
而不是在扩展名中调用'{{asset}}'
,只需调用公共功能getAssetUrl()
Instead of calling '{{asset}}'
in your extension, just call the public function getAssetUrl()
这篇关于使用Symfony2在Twig Extension中包含资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!