【问题标题】:Defining Liquid tag, returning string works but processing to return string doesn't?定义 Liquid 标签,返回字符串有效,但处理返回字符串无效?
【发布时间】:2014-09-26 12:35:31
【问题描述】:

我是 Liquid 新手,但不是 Ruby,而且出于安全原因,我知道 Liquid 不一定是 Ruby。但是,在 Jekyll 博客中,我尝试将以下代码定义为插件:

module Jekyll
  class Person_Index < Liquid::Tag

    def initialize(tag_name, text, tokens)
      super
      @text = text
    end

    def render(context)
      for person in context.registers[:site].data["people"]

        if (person.index.to_s() == @text.to_s())
            return person.display
        end    
      end

      # We reach here, something's wrong anyway
      return "(( INDEX NOT FOUND #{@text} ))"
    end
  end
end

Liquid::Template.register_tag('Person_Index', Jekyll::Person_Index)

不出所料,这在文档生成期间会失败。将其称为{% Person_Index 2 %} 会给我这个错误:

Liquid Exception: wrong number of arguments (0 for 1) in _posts/2014-07-22-an-entry.md/#excerpt

我确定有人在想“也许它以某种方式被错误的摘录一代抓住了”。我通过简单地用第二段作为测试用例重写它来尝试这种解决方法;它仍然给出同样的错误,只是不再出现在#excerpt 中。

直接更改渲染以使其成为单行将使其毫不犹豫地运行,并输出“很好”(我用引号表示,因为这不是所需的行为):

    def render(context)
      return "HOW ARE YOU BECAUSE I AM A POTATO"
    end

在调用标签的地方,这将输出从 Portal 2 提升的行就好了。 (是的,我知道 return 在 ruby​​ 中是不必要的,对每个人来说都是不必要的。)

为什么第一个失败而第二个有效?有没有办法做第一个似乎想做的事情?

_data/people.yml 的定义类似于:

-   index: 1
    nick:    Guy
    display: That Guy
    name:
        first:  That
        middle: One
        last:   Guy
    account:
        github: greysondn

-   index: 2
    nick:    Galt
    display: Johnny
    name:
        first:  John
        middle: 
        last:   Galt
    account:
        github: 

提前谢谢你。

【问题讨论】:

    标签: ruby exception jekyll liquid argument-error


    【解决方案1】:

    我发现了问题:

    if (person.index.to_s() == @text.to_s())
      return person.display
    end
    

    在这里,您的代码尝试在 person 上使用 index 方法。 person.['index'].to_s() 更好。 person.display =&gt; person['display'] 也一样

    到这里后,person.index.to_s() == @text.to_s() 仍然存在问题。由于您的液体标签是{% Person_Index 2 %}@text 是带有空格的“2”。 所以“2”!=“2”。我们需要剥离字符串:

    if (person['index'].to_s().strip == @text.to_s().strip)
    

    很好,但我更喜欢

    if (person['index'].to_i() == @text.to_i())
        return person['display']
    end
    

    【讨论】:

    • person.index.to_s(),其中index 被访问为 attribute 我认为..? (您的解决方案说 parameter,含义略有不同,但如果我是正确的,未来的读者可能会感到困惑。)除此之外,这是正确的解决方案。我接受了转换为整数的建议(使用to_i())进行比较,现在它就像一个魅力。谢谢你的帮助,大卫!
    • 附录:person 是一个hash,所以我们需要给它key 来取回值。我试图将其视为任意对象。我不确定 Ruby 是否有用于此类访问的命名法。这就是从person.display 更改为person['display'] 的原因——我们必须将其作为键,而不是尝试将其作为值访问。关于剥离的建议是合理的;我对其进行了测试,但没有尝试剥离(因为强制转换为整数是有道理的)...我想不出其他可能对这里的未来人有用的注释...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 2022-11-12
    • 1970-01-01
    • 2018-02-27
    相关资源
    最近更新 更多