【问题标题】:Custom liquid block retrieving context variables自定义液体块检索上下文变量
【发布时间】:2018-07-13 18:33:40
【问题描述】:

如何在 jekyll markdown 的自定义 Liquid 块中检索分配的变量?

我读过using assignments in templates,但我显然缺少一些简单的东西。

编辑:这仅发生在 Jekyll 变量中,而不是在液体中设置的基本变量。

不起作用:

ma​​rkdown中的液体块:

{% assign variable = site.variables | where "someval", "true" %}

{% customblock variable %}
{% endcustomblock %}

Jekyll 插件:

module Jekyll
  module Tags
    class CustomBlockTag < Liquid::Block

      def initialize(tag_name, variable_name, options)
        super
        @variable = variable_name
      end

      def render(context)
          puts context.scopes
          puts context.key?(@variable)
          puts context.find_variable(@variable)
          puts context[@variable] 
      end
    end
  end
end

Liquid::Template.register_tag('customblock', Jekyll::Tags::CustomBlockTag)

输出:

{..., "variable"=> {<another map>} }
true
<blank>
<blank>

我不经常使用 ruby​​,但据我在source 中看到的,它只是包装了字典查找。我在这里错过了什么?


以下工作正常

ma​​rkdown中的液体块:

{% assign variable = "1" %}

{% customblock variable %}
{% endcustomblock %}

Jekyll 插件:

module Jekyll
  module Tags
    class CustomBlockTag < Liquid::Block

      def initialize(tag_name, variable_name, options)
        super
        @variable = variable_name
      end

      def render(context)
          puts context.scopes
          puts context.key?(@variable)
          puts context.find_variable(@variable)
          puts context[@variable] 
      end
    end
  end
end

Liquid::Template.register_tag('customblock', Jekyll::Tags::CustomBlockTag)

输出:

{..., "variable"=>"1"}
true
1
1

【问题讨论】:

    标签: ruby jekyll liquid


    【解决方案1】:

    事实证明,有一些红鲱鱼是问题所在:

    • 我的variable实际上是一个Drop,并不是一个普通的哈希值。具体来说,它是一个DocumentDrop,它将to_s 委托给Document 类。
    • to_s 的实现打印出Documentoutputcontent"NO CONTENT"
    • 在我的例子中,outputcontent 是空格或换行符,所以这就是输出的全部内容。这是因为文件只存在于它们的前面,所以没有实际内容。
    • 通过 Drop 接口访问前面的内容。所以我实际上得到了variable,它只是一个空字符串表示。
    • 事不宜迟,获取前沿数据context[@variable]["my-front-matter-data"]

    好吧,至少我现在感觉不那么像红宝石新手了。

    【讨论】:

    • 干得好。恭喜你解决了
    【解决方案2】:

    尝试将{% assign variable = site.variables | where "someval", "true" %} 更改为{% assign variable = site.variables | where: "someval", "true" %}

    此外,根据docsvariable 似乎不是一个选项。如果你想传递更多信息,你需要使用 site.data 之类的东西或在你的 jekyll 初始化程序中定义的信息(通常称为 _config.yml)。

    【讨论】:

    • 我的 MCVE 是仓促编写的。见编辑。我确实用我的实际代码尝试了这个,并得到了同样没有价值的意外结果。
    • 我会将此标记为正确,因为我认为这只是不受支持的用法。我相信 jekyll/liquid 更喜欢用户使用现有的液体块并从液体模板访问 jekyll 数据,而不是将 jekyll 数据直接传递到插件系统中。这很不幸,因为它需要更多的复制和粘贴。
    猜你喜欢
    • 2018-06-19
    • 2016-08-25
    • 2016-07-07
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2011-09-15
    相关资源
    最近更新 更多