我無法弄清楚如何在jekyll插件中創建過濾器或標籤,以便我可以返回一個目錄並循環其內容。我發現這些:返回Jekyll插件目錄中的文件列表?
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 %}
我將需要能夠不斷爲我將在網站上使用的各種集合返回事物的數組。我只需要一個準系統插件即可。
謝謝!
更新:我部分解決了它。此方法可行,但需要使用endloop_directory而不是endfor,這對我來說似乎有點難看。另外,由於無法在html中轉義{},因此過濾器無法獲取像*。{jpg,png}這樣的參數。打開關於如何在屬性中傳遞正則表達式字符串的建議...
#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)
我猜所有的反對票都是因爲這是一個評論,而不是對問題的回答。 – jbranchaud 2013-03-15 20:56:28