我不知道如何在 jekyll 插件中创建过滤器或标签,以便我可以返回目录并循环其内容。我找到了这些:
http://pastebin.com/LRfMVN5Y http://pastebin.com/LRfMVN5Y
http://snippets.dzone.com/posts/show/302 http://snippets.dzone.com/posts/show/302
到目前为止我有:
module Jekyll
class FilesTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text
end
def render(context)
#"#{@text} #{Time.now}"
Dir.glob("images/*").each { |i| "#{i}" }
#Dir.glob("images/*")
#Hash[*Dir.glob("images/*").collect { |v| [v, v*2] }.flatten]
end
end
end
Liquid::Template.register_tag('files', Jekyll::FilesTag)
我可以成功地将图像列表作为字符串返回并使用以下命令打印:
{% files test_string %}
但对于我来说,无论我如何从 Dir.glob 返回数组/哈希,我都无法循环数组。我只想能够做到:
{% for image in files %}
image
{% endfor %}
我需要能够为我将在网站上使用的各种集合不断返回事物数组。我只需要一个准系统插件来构建。
Thanks!
更新:我部分解决了它。此方法有效,但需要使用 endloop_directory 而不是 endfor,这对我来说似乎有点难看。此外,过滤器无法接受 *.{jpg,png} 这样的参数,因为无法转义 html 中的 {}。接受有关如何在属性中传递正则表达式字符串的建议......
#usage:
#{% loop_directory directory:images iterator:image filter:*.jpg sort:descending %}
# <img src="{{ image }}" />
#{% endloop_directory %}
module Jekyll
class LoopDirectoryTag < Liquid::Block
include Liquid::StandardFilters
Syntax = /(#{Liquid::QuotedFragment}+)?/
def initialize(tag_name, markup, tokens)
@attributes = {}
@attributes['directory'] = '';
@attributes['iterator'] = 'item';
@attributes['filter'] = 'item';
@attributes['sort'] = 'ascending';
# Parse parameters
if markup =~ Syntax
markup.scan(Liquid::TagAttributes) do |key, value|
@attributes[key] = value
end
else
raise SyntaxError.new("Bad options given to 'loop_directory' plugin.")
end
#if @attributes['directory'].nil?
# raise SyntaxError.new("You did not specify a directory for loop_directory.")
#end
super
end
def render(context)
context.registers[:loop_directory] ||= Hash.new(0)
images = Dir.glob(File.join(@attributes['directory'], @attributes['filter']))
if @attributes['sort'].casecmp( "descending" ) == 0
# Find files and sort them reverse-lexically. This means
# that files whose names begin with YYYYMMDD are sorted newest first.
images.sort! {|x,y| y <=> x }
else
# sort normally in ascending order
images.sort!
end
length = images.length
result = []
context.stack do
images.each_with_index do |item, index|
context[@attributes['iterator']] = item
context['forloop'] =
{
'name' => @attributes['iterator'],
'length' => length,
'index' => index + 1,
'index0' => index,
'rindex' => length - index,
'rindex0' => length - index - 1,
'first' => (index == 0),
'last' => (index == length - 1)
}
result << render_all(@nodelist, context)
end
end
result
end
end
end
Liquid::Template.register_tag('loop_directory', Jekyll::LoopDirectoryTag)