{% directory_list directory:products/tea iterator:item sort:descending %}
{{ item }}
{% enddirectory_list %}
Created
January 21, 2016 10:52
-
-
Save moabi/72ca686ec455fd264911 to your computer and use it in GitHub Desktop.
Jekyll - list directories from a path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#usage: | |
#{% directory_list directory:products/tea iterator:item sort:descending %} | |
# {{ item }} | |
#{% enddirectory_list %} | |
module Jekyll | |
class DirectoryListingTag < Liquid::Block | |
include Liquid::StandardFilters | |
Syntax = /(#{Liquid::QuotedFragment}+)?/ | |
def initialize(tag_name, markup, tokens) | |
@attributes = {} | |
@attributes['directory'] = ''; | |
@attributes['iterator'] = '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 | |
super | |
end | |
def render(context) | |
context.registers[:loop_directory] ||= Hash.new(0) | |
directory = Dir.glob("#{@attributes['directory']}/*").select {|f| File.directory? f} | |
if @attributes['sort'].casecmp( "descending" ) == 0 | |
directory.sort! {|x,y| y <=> x } | |
else | |
# sort normally in ascending order | |
directory.sort! | |
end | |
result = [] | |
context.stack do | |
directory.each { |pathname| | |
context[@attributes['iterator']] = File.basename(pathname) | |
result << render_all(@nodelist, context) | |
} | |
end | |
result | |
end | |
end | |
end | |
Liquid::Template.register_tag('directory_list', Jekyll::DirectoryListingTag) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment