Monday, December 10, 2012

Reload Cached CSS / JS Files in Symfony

An elegant way to force browsers to reload cached CSS / JS files in Symfony 1.4

settings.yml
Add Asset, CSSCache, JSCache to the standard_helpers row:
standard_helpers: [ Partial, Cache, I18N, Date, Asset, CSSCache, JSCache ]
lib/helper/CSSCacheHelper.php
function include_versioned_stylesheets()
{
  $response = sfContext::getInstance()->getResponse();
  sfConfig::set('symfony.asset.stylesheets_included', true);
  $html = '';
  foreach ($response->getStylesheets() as $file => $options) {
    $filepath = sfConfig::get('sf_web_dir') . '/' .  stylesheet_path($file);
    if(file_exists($filepath)) {
      $file .= '?v=' . filectime($filepath);
    }
    $html .= stylesheet_tag($file, $options);
  }
  echo $html;
}
lib/helper/JSCacheHelper.php
function include_versioned_javascripts()
{
  $response = sfContext::getInstance()->getResponse();
  sfConfig::set('symfony.asset.javascripts_included', true);
  $html = '';
  foreach ($response->getJavascripts() as $file => $options) {
    $filepath = sfConfig::get('sf_web_dir') . '/' .  javascript_path($file);
    if(file_exists($filepath)) {
      $file .= '?v=' . filectime($filepath);
    }
    $html .= javascript_include_tag($file, $options);
  }
  echo $html;
}
apps/xxx/templates/layout.php
Use the include_versioned_stylesheets() and include_versioned_javascripts() functions to load css and js files, instead of the default include_stylesheets() and include_javascripts() functions.

No comments:

Post a Comment