Я не могу понять, как создать фильтр или тег в плагине 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, что мне кажется немного некрасивым. Кроме того, фильтр не может принимать такие параметры, как *.{jpg,png}, потому что нет способа избежать {} в html. Открыт для предложений о том, как передать строку регулярного выражения в атрибуте...
#usage:
#{% loop_directory directory:images iterator:image filter:*.jpg sort:descending %}
#
#{% 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)