From 4de2be8c5fd6c81d1065479d34602d7521219c0e Mon Sep 17 00:00:00 2001 From: Parker Moore Date: Tue, 22 Apr 2014 12:50:04 -0400 Subject: [PATCH] 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. --- lib/jekyll.rb | 1 + lib/jekyll/liquid_extensions.rb | 22 ++++++++++++++++++++++ test/test_liquid_extensions.rb | 31 +++++++++++++++++++++++++++++++ test/test_utils.rb | 1 + 4 files changed, 55 insertions(+) create mode 100644 lib/jekyll/liquid_extensions.rb create mode 100644 test/test_liquid_extensions.rb diff --git a/lib/jekyll.rb b/lib/jekyll.rb index caa492fe..b9bf4f67 100644 --- a/lib/jekyll.rb +++ b/lib/jekyll.rb @@ -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' diff --git a/lib/jekyll/liquid_extensions.rb b/lib/jekyll/liquid_extensions.rb new file mode 100644 index 00000000..5ba7dd8e --- /dev/null +++ b/lib/jekyll/liquid_extensions.rb @@ -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 diff --git a/test/test_liquid_extensions.rb b/test/test_liquid_extensions.rb new file mode 100644 index 00000000..2395a8de --- /dev/null +++ b/test/test_liquid_extensions.rb @@ -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 diff --git a/test/test_utils.rb b/test/test_utils.rb index cfd6c4a6..829ba2d8 100644 --- a/test/test_utils.rb +++ b/test/test_utils.rb @@ -63,4 +63,5 @@ class TestUtils < Test::Unit::TestCase end end + end