2016-11-16 75 views
2

我无法理解为什么我的下面的代码部分失败。我尝试为Jekyll创建Liquid标签。当设置类成员“text”时,成员“xyz”根本没有设置。但为什么?Ruby:为什么我的成员没有设置初始化?

module MyModule 
    class MyTag < Liquid::Tag 
    def initialize(tag_name, text, tokens) 
     super 
     @text = text 
     @xyz = "HELLO" 
    end 

    def render(context) 
     "Output #{@text} #{@xyz}" 
    end 
    end 
end 

Liquid::Template.register_tag('my_tag', MyModule::MyTag) 

随着调用上述以下

{% my_tag de 1234 %} 

输出是:

Output de 1234 

我认为应该有 “HELLO”,以及像:

Output de 1234 HELLO 

我错过了什么?

来自the Liquid class is here的原始码。

+0

从代码来看,我预计“输出去HELLO”,而不是“输出去1234 HELLO” 。 –

+0

@SergioTulentsev不,它和我上面写的完全一样。该论点被视为完整的字符串。你必须将自己的观点与Liquid分开(人们说)。 – Christian

+0

如果将“#输出#{@文本}#{@ xyz}”'更改为'“输出#{@ text}'#{@ xyz}'”',会发生什么? –

回答

2

您的代码看起来工作正常使用Ruby 2.1.5和液体3.0​​.6:

require 'liquid' 
module MyModule 
    class MyTag < Liquid::Tag 
    def initialize(tag_name, text, tokens) 
     super 
     @text = text 
     @xyz = "HELLO" 
    end 

    def render(context) 
     "Output #{@text} #{@xyz}" 
    end 
    end 
end 

Liquid::Template.register_tag('my_tag', MyModule::MyTag) 

@template = Liquid::Template.parse("{% my_tag de 1234 %}") 
puts @template.render 
#=> "Output de 1234 HELLO" 
+0

我可以确认我有相同的输出从CLI运行它。与Jekyll结合使用时,它仍然存在问题。 – Christian