php - 在 Symfony2 和 Twig 中为文件添加资源路径前缀

标签 php symfony twig assets

我将文件上传到 web/files/images/ 并尝试使用 asset 函数链接它们:

<img src='{{ asset(article.image) }}'/>

但这会产生类似 /img1.jpg
的 URL 我需要为资源 URL 添加前缀(设置基本文件夹)以强制其生成 /files/images/img1.jpg
如何为 asset 网址添加前缀?

最佳答案

虽然您可以轻松地为此目的引入一个新的 Twig 变量(即在您的基本模板中)...

{% set asset_base = '//files/images' %}

...或创建一个静态全局 Twig 变量...

# app/config/config.yml
twig:
    globals:
        asset_base: //files/images

...然后在 img 标签的 src 属性中使用它...

<img src='{{ asset_base }}{{ asset(article.image) }}'/>

...symfony2 已经以 assets_base_urls 指令的形式提供了此功能:

# app/config/config.yml
framework:
    templating:
        assets_base_urls:
            http:   [http://domain/files/images]
            ssl:    [https://domain/files/images]

您还可以通过提供协议(protocol)相关 url 来同时设置基本 url:

framework:
    templating:
        assets_base_urls: //files/images

有关该指令的更多信息可以在文档章节 FrameworkBundle Configuration#assets-base-urls 中找到。

关于php - 在 Symfony2 和 Twig 中为文件添加资源路径前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874303/

相关文章:

php - Symfony2 在数据库驱动程序上给出了 ParameterNotFoundException

php - Symfony2 删除记录实体问题

rest - FOS 休息包 : unable to find template

Symfony2,如果 Controller 有构造函数,如何在 Twig 模板中呈现 Controller 的 Action

html - 如何对齐标签和单选按钮?

php - Twig 标签包含 vs 函数包含

PHP : Convert dynamic uploaded image to specific color(dynamic color)

php - Laravel thujohn/pdf ID 已在 DOM 中定义

php - 集中 php 全局变量?

php - 复制演示 "You cannot define a sequence item when in a mapping"时出错