0

我是 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红宝石是不必要的,每个人都有。)

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

_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: 

先感谢您。

4

1 回答 1

1

我发现了问题:

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

在这里,您的代码尝试在person上使用index方法。更好。相同的person.['index'].to_s()person.display => 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
于 2014-09-26T15:05:38.447 回答