简体   繁体   English

在Twig Extension中使用locateResource

[英]Using locateResource inside Twig Extension

I wish to use the following inside of a Twig Extension 我希望在Twig Extension中使用以下内容

$kernel = $container->getService('kernel');
$path = $kernel->locateResource('@AdmeDemoBundle/path/to/file/Foo.png');

but this involved passing in the Kernel, which is bad. 但这涉及传递内核,这很糟糕。 Plus I could not get it to work anyway when trying this method. 另外,尝试这种方法时,我还是无法正常工作。

How can I access a resources path within a Twig Extension? 如何访问Twig Extension中的资源路径?

The Extension is already a Service. 该扩展已经是一项服务。 I can use Assetic to give me the URL, but I really want the path. 我可以使用Assetic来给我URL,但是我确实想要路径。

I had a similar need: i needed to pass to the filter the url of an image to display it in a for loop and build a string. 我有一个类似的需求:我需要将图像的url传递给过滤器,以在for循环中显示它并构建一个字符串。

I passed the URL directly to the filter in this way: 我以这种方式将URL直接传递给过滤器:

{%  image '@AppBundle/Resources/public/images/my_asset.png' %}
    {% set resolved_asset_url = asset_url %}
{% endimage %}

{{ my_var|filter_name(resolved_asset_url)|raw(html) }}

In this way the Twig template resolve the correct resource's URL, sets it as a variable, and then I pass it to the filter from inside the template itself, without having to deal with kernel or something else. 这样,Twig模板解析了正确资源的URL,将其设置为变量,然后从模板本身内部将其传递给过滤器,而无需处理kernel或其他问题。

If you want just to serve a download, you should create a Route that accomplishes that task. 如果您只想提供下载服务,则应创建一个完成该任务的路由。

In this way, you'll call the locator inside the route, and a simple 这样,您将在路线内调用定位器,

{{ path('route_that_does_the_locator_thing') }}

will be fine. 会没事的。

If you need instead to include a file in your template (ex. CSS, JS..), you need to declare your file as an asset, maybe using Assetic. 如果您需要在模板中包含文件(例如CSS,JS ..),则需要使用Assetic将文件声明为资产。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM