简体   繁体   English

如何创建带有 for 循环的 Liquid 标签?

[英]How do I create a Liquid tag with a for-loop?

So, I'd like to create an.rb plugin for a Jekyll theme to be able to use the following Liquid syntax in.md files:所以,我想为 Jekyll 主题创建一个 .rb 插件,以便能够在 .md 文件中使用以下 Liquid 语法:

{% tab caption %}

which, when building a webpage from an.md file, should convert into:在从 .md 文件构建网页时,应将其转换为:

<p><b>Tab. X.</b> Caption</p>

where X is the counting number of each particular {% tab caption %} tag in the document;其中 X 是文档中每个特定{% tab caption %}标签的计数; caption is the value for a key from a predefined hash, where the key matches the caption in the tag. caption 是预定义 hash 中键的值,其中键与标签中的caption相匹配。

Say, I have the following code in.md:比如说,我在 .md 中有以下代码:

The table below summarizes diagram symbols.

{% tab diagram %}

The table below presents the configuration options.

{% tab config %}

Which should return:哪个应该返回:

The table below summarizes diagram symbols.
<p><b>Tab. 1.</b> Diagram designations.</p>
The table below presents the configuration options.
<p><b>Tab. 2.</b> Configuration options.</p>

I've figured out value retrieval from hash quite easily;我已经很容易地从 hash 中找出价值检索; however, I can't figure out how to do the numbering.但是,我不知道如何进行编号。 I assume I could for-loop through an array of the occurrences of this particular tag;我假设我可以循环遍历这个特定标签出现的数组; however, I haven't managed to successfully google making such an array in the first place.然而,我一开始并没有成功地通过谷歌搜索来制作这样一个数组。

Thanks for your attention!感谢您的关注!

I've figured out how to do what I wanted.我已经想出如何做我想做的事了。 It did not require any looping after all:毕竟它不需要任何循环:

module Jekyll
    class TabHandler < Liquid::Tag
        @@count = 1

        def initialize(name, input, tokens)
            super
            @input = input
        end

        def render(context)
            modulename = context["modulename"].to_s
            dictionary = { "io " => "I/O specifications for " + modulename,
                "se " => modulename + " signal exchange",
                "diagram " => "Diagram designations" }
            if dictionary.has_key?(@input)
                output = "<p><b>Tab. " + @@count.to_s + ".</b> " + dictionary.fetch(@input) + ".</p>"
                @@count += 1
            else
                output = "<p><b>Tab. " + @@count.to_s + ".</b> " + @input + ".</p>"
                @@count += 1
            end
            return output
        end
    end
end

Liquid::Template.register_tag('tab', Jekyll::TabHandler)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM