css - 在 symfony 中为图像添加修订号以避免浏览器缓存

标签 css image symfony-1.4 browser-cache

我想通过在每个图像后附加 SVN 修订号来避免浏览器缓存我的图像(与 this answser 的方式相同):

<?php $v = getRevisionNumber() ?>
<img src="picture.jpg?v=<?= $v ?>" alt="">

有没有办法在 Symfony 1.4 中自动执行此操作(like this 对于 js/css,但使用图像代替)

此外,我该如何为 css 文件中的图像执行此操作?

#title {
    background-image: url(/images/title.png);
}

最佳答案

我在 symfony 跟踪器中发现了一些有趣的东西,对于 1.3/1.4 版本,有一个补丁可以自动为 web 目录中的所有文件添加时间戳:http://trac.symfony-project.org/ticket/6135

它已经被恢复,不知道为什么......(侵入?)。

覆盖默认 Assets 助手

无论如何,我认为您必须创建自己的 AssetHelper(复制当前的所有内容)并将补丁 #6135 添加并自定义到 lib/helper/CustomAssetHelper.php 中.

但是您无法卸载 AssetHelper,因为它会自动加载到核心中:http://trac.symfony-project.org/browser/branches/1.4/lib/view/sfPHPView.class.php#L33所以会有冲突,因为您将有重复的功能(在 AssetHelper 和 CustomAssetHelper 中)。

添加自定义模板引擎

想法是有一个自定义 sfPHPView重新定义 loadCoreAndStandardHelpers调用您自己的 Assets 助手(将其放入 lib/view/sfCustomPHPView.class.php ):

class sfCustomPHPView extends sfPHPView
{
  /**
   * Loads core and standard helpers to be use in the template.
   */
  protected function loadCoreAndStandardHelpers()
  {
    static $coreHelpersLoaded = 0;

    if ($coreHelpersLoaded)
    {
      return;
    }

    $coreHelpersLoaded = 1;

    $helpers = array_unique(array_merge(array('Helper', 'Url', 'CustomAsset', 'Tag', 'Escaping'), sfConfig::get('sf_standard_helpers')));

    // remove default Form helper if compat_10 is false
    if (!sfConfig::get('sf_compat_10') && false !== $i = array_search('Form', $helpers))
    {
      unset($helpers[$i]);
    }

    $this->context->getConfiguration()->loadHelpers($helpers);
  }
}

要更改默认的 sfPHPView,您需要添加 module.ymlconfig/apps/frontend/config/具有以下内容 ( inspired from sfTwigPlugin ):

all:
  view_class: sfCustom

覆盖所有image_tag()

正如 Yzmir Ramirez 所说,image_tag()电话 image_path()哪个电话_compute_public_path($source, 'images', 'png', $absolute); .

_compute_public_path函数,在最后一个条件之前,您自定义 query_string 以添加您自己的修订号(将在其他地方定义 - 例如 sfConfig):

$file = sfConfig::get('sf_web_dir').$source;
if ('images' == $dir && sfConfig::get('my_revision_number'))
{
  $query_string .= sfConfig::get('my_revision_number');
}

它可能有点复杂,但使用这种方式,您可以覆盖 image_tag 函数并添加您想要的版本号,而无需重新定义所有 image_tag() 调用。

关于 CSS 中的图像,它有点复杂,因为您必须解析 css 或在 PHP 中编写 css。不知道最好的方法。

关于css - 在 symfony 中为图像添加修订号以避免浏览器缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9755377/

相关文章:

php - 如何在 symfony 重定向中获取 referer url

php - 如何检测用户是否已登录 symfony?

php - 推进类重建后 "Base Query"内的多个函数声明

c# - 如何在mvc中单击按钮重定向到另一个页面和特定div

python - 使用opencv编写pgms时如何更改最大灰度的默认值?

ios - 图像在 iPhone 8 和 8 plus 上呈现不同

ios - 我可以将图像从我的应用程序复制到 iOS 中的邮件应用程序吗

jquery - 使用 jquery 在 div 上滚动时更改 anchor 类

CSS 主体 `background-image` 在 Chrome、Safari (webkit) 上右对齐

javascript - 可拖动滚动和移动设备上的潜在问题