1

如何使用 Nanoc 实现缓存清除?

例如,将 MD5 校验和添加到 HTML 和 CSS 文件上的所有 image/font/js/etc 资源链接。例如,如果我有index.htmland images/badger.jpg,我希望页面上的图片链接更改为类似

`href="images/badger.jpg?12345"`

假设 12345 是 badger.jpg 的正确 MD5 哈希。

4

2 回答 2

2

您可以采用路由方法。我建议使用实际不同的文件名而不是查询字符串 - 一些 http 缓存不会缓存带有查询字符串的 url。

route '/stylesheet/' do
  csum = [File.open(item[:filename]).read.checksum]
  # add other files you include from your stylesheet.less (if you use less)
  csum += Dir['content/styles/*'].select { |i| File.file?(i) }.map { |f| File.read(f).checksum }
  '/style-' + csum.checksum + '.css'
end

route '*' do
  ext = item[:extension]
  versionexts = ['css','js']

  if versionexts.include?(ext)
    # versioned filenames, depending on the checksum of the source file
    # these files shouldn't depend on other sources, or you have to checksum them too (see above)
    item.identifier.chop + '-' + File.read(item[:filename]).checksum + '.' + ext
  elsif item.binary?
    # Write item with identifier /foo/ to /foo.ext
    item.identifier.chop + '.' + ext
  else
    # Write item with identifier /foo/ to /foo/index.html
    item.identifier + 'index.html'
  end
end

您不能在路由中使用生成内容的校验和,因为路由是在编译之前完成的。

于 2013-01-25T09:21:02.860 回答
2

Arjan van der Gaag 专门为此制作了一颗宝石:https ://github.com/avdgaag/nanoc-cachebuster

引用这个人自己的话

使用很简单,只需要安装gem:

$ gem install nanoc-cachebuster 

并需要 gem 并包括助手才能开始:

# in default.rb
require 'nanoc3/cachebuster' 
include Nanoc3::Helpers::CacheBusting 

您现在可以在路由规则中使用 #fingerprint 方法:

route '/assets/styles/' do
  item.identifier.chop + fingerprint(item) + '.' + item[:identifier]
end

gem 将确保在您编译站点时更新对您指纹文件的引用。

于 2013-04-26T17:46:33.507 回答