0

In Kohana, is there a quick and easy way to use the HTML::style() helper to automatically include a UNIX timestamp mtime of a file after the CSS or JS file name in the case of a script?

In CakePHP, I would just use the HTML/css helper and this in the configuration:

Configure::write('Asset.timestamp', 'force');

This way when doing the following:

echo $this->Html->css('styles');

It would output:

<link rel="stylesheet" type="text/css" href="/css/styles.css?1338350352" />

Expedito
  • 7,771
  • 5
  • 30
  • 43
Thomas Farvour
  • 1,103
  • 2
  • 11
  • 24

1 Answers1

1

I use this in my every project:

class HTML extends Kohana_HTML
{

    /**
     *  Given a file, i.e. /css/base.css, replaces it with a string containing the
     *  file's mtime, i.e. /css/base.1221534296.css.
     *  
     *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
     *                starting with slash).
     */
    public static function auto_version($file)
    {
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $file))
            return $file;

        $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . '/' . $file);
        return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
    }

}

In my template view:

<link type="text/css" href="<?php echo HTML::auto_version('/media/css/global.css') ?>" rel="stylesheet" />

Credits go to Kip answer from How to force browser to reload cached CSS/JS files?

PS. Remember to add below rule to your .htaccess:

RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
Community
  • 1
  • 1
matino
  • 17,199
  • 8
  • 49
  • 58