Add Jekyll::LiquidExtensions.lookup_variable
To use, just include `Jekyll::LiquidExtensions` as you please: ```ruby class SayHi < Liquid::Tag include Jekyll::LiquidExtensions def initialize(tag_name, markup, tokens) @markup = markup.strip end def render(context) "hi #{lookup_variable(context, @markup)}" end end ``` Fixes #2071.
This commit is contained in:
parent
68d491c40d
commit
4de2be8c5f
|
@ -61,6 +61,7 @@ require 'jekyll/plugin'
|
|||
require 'jekyll/converter'
|
||||
require 'jekyll/generator'
|
||||
require 'jekyll/command'
|
||||
require 'jekyll/liquid_extensions'
|
||||
|
||||
require_all 'jekyll/commands'
|
||||
require_all 'jekyll/converters'
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
module Jekyll
|
||||
module LiquidExtensions
|
||||
|
||||
# Lookup a Liquid variable in the given context.
|
||||
#
|
||||
# context - the Liquid context in question.
|
||||
# variable - the variable name, as a string.
|
||||
#
|
||||
# Returns the value of the variable in the context
|
||||
# or the variable name if not found.
|
||||
def lookup_variable(context, variable)
|
||||
lookup = context
|
||||
|
||||
variable.split(".").each do |value|
|
||||
lookup = lookup[value]
|
||||
end
|
||||
|
||||
lookup || variable
|
||||
end
|
||||
|
||||
end
|
||||
end
|
|
@ -0,0 +1,31 @@
|
|||
require 'helper'
|
||||
|
||||
class TestLiquidExtensions < Test::Unit::TestCase
|
||||
|
||||
context "looking up a variable in a Liquid context" do
|
||||
class SayHi < Liquid::Tag
|
||||
include Jekyll::LiquidExtensions
|
||||
|
||||
def initialize(tag_name, markup, tokens)
|
||||
@markup = markup.strip
|
||||
end
|
||||
|
||||
def render(context)
|
||||
"hi #{lookup_variable(context, @markup)}"
|
||||
end
|
||||
end
|
||||
Liquid::Template.register_tag('say_hi', SayHi)
|
||||
setup do
|
||||
@template = Liquid::Template.parse("{% say_hi page.name %}") # Parses and compiles the template
|
||||
end
|
||||
|
||||
should "extract the var properly" do
|
||||
assert_equal @template.render({'page' => {'name' => 'tobi'}}), 'hi tobi'
|
||||
end
|
||||
|
||||
should "return the variable name if the value isn't there" do
|
||||
assert_equal @template.render({'page' => {'title' => 'tobi'}}), 'hi page.name'
|
||||
end
|
||||
end
|
||||
|
||||
end
|
|
@ -63,4 +63,5 @@ class TestUtils < Test::Unit::TestCase
|
|||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue