Improved: config_tag plugin is much more flexible now and can be used by other plugins directly through the config_tag method

This commit is contained in:
Brandon Mathis 2013-03-11 01:19:35 -05:00
parent 2bec7f858a
commit 05db158fec

View File

@ -3,27 +3,42 @@ require 'json'
class ConfigTag < Liquid::Tag class ConfigTag < Liquid::Tag
def initialize(tag_name, options, tokens) def initialize(tag_name, options, tokens)
super super
@options = options.split(' ').map {|i| i.strip } options = options.split(' ').map {|i| i.strip }
@key = @options.first @key = options.slice!(0)
@tag = (@options[1] || 'div') @tag = nil
@classname = nil
options.each do |option|
@tag = $1 if option =~ /tag:(\S+)/
@classname = $1 if option =~ /classname:(\S+)/
end
end end
def render(context) def render(context)
config = context.registers[:site].config config_tag(context.registers[:site].config, @key, @tag, @classname)
options = @options.first.split('.').map { |k| config = config[k] }.last #reference objects with dot notation end
keyclass = @key.sub(/_/, '-').sub(/\./, '-') end
tag = "<#{@tag} class='#{keyclass}'"
def config_tag(config, key, tag=nil, classname=nil)
options = key.split('.').map { |k| config[k] }.last #reference objects with dot notation
tag ||= 'div'
classname ||= key.sub(/_/, '-').sub(/\./, '-')
output = "<#{tag} class='#{classname}'"
if options.respond_to? 'keys'
options.each do |k,v| options.each do |k,v|
unless v.nil? unless v.nil?
v = v.join ',' if v.respond_to? 'join' v = v.join ',' if v.respond_to? 'join'
v = v.to_json if v.respond_to? 'keys' v = v.to_json if v.respond_to? 'keys'
tag += " data-#{k.sub'_','-'}='#{v}'" output += " data-#{k.sub'_','-'}='#{v}'"
end end
end end
tag += "></#{@tag}>" elsif options.respond_to? 'join'
p tag output += " data-value='#{config[key].join(',')}'"
tag else
output += " data-value='#{config[key]}'"
end end
output += "></#{tag}>"
end end
Liquid::Template.register_tag('config_tag', ConfigTag) Liquid::Template.register_tag('config_tag', ConfigTag)