开发者

how could i use ETag in smarty?

开发者 https://www.devze.com 2023-03-05 20:37 出处:网络
I use smarty as my template engine and YSlow ( Firefox addon) report me that my Etag 开发者_JAVA百科flag is \"F\" But i use smarty.

I use smarty as my template engine and YSlow ( Firefox addon ) report me that my Etag 开发者_JAVA百科flag is "F" But i use smarty. how could i use Etag with smarty and my main tpl is framework.tpl and all other templates assign to it


If you decide that you actually need ETags on your pages (which is different from implementing them just to pass a somewhat arbitrary test), I've had good experience with this (older) script: http://simonwillison.net/2003/Apr/23/conditionalGet/

Note that this is not really Smarty-specific, as Smarty deals with page templates; this whole "conditional request" business (with ETag and Last-Modified and whatnot) happens in HTTP headers, so the code above is just plain PHP.

You need to determine the last modification time of your resource (which may be different from file modification - e.g. when was the last time the relevant part of the database changed?), and pass it to doConditionalGet($timestamp); it will then either send a 304 and terminate, or return back to you (which means you need to do the full page processing, as if there wasn't any conditional request).


Simply but the directive

FileETag None

in your .htaccess file to disable the ETag header field. YSlow will no longer complain... :)


You can use an output filter in Smarty. Below some ready-to-use code for ETagging:

function etag_handler($output)
{
    $etag = md5($output);
    header('ETag: '.$etag);
    if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $etag) !== FALSE)
    {
        header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
        return '';
    }
    return $output;
}

$smarty->registerFilter('output', 'etag_handler');

Put that somewhere before $smarty->display(...);.

Note, that with this code the server still computes the output, but if the client has already the identical answer, the server won't send it again, so it's just a network traffic saver. If you want to save computing power in the server, you have to do something else (caching), but you can combine it with ETagging.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号