Home > Net >  How do I create a Liquid tag with a for-loop?
How do I create a Liquid tag with a for-loop?

Time:02-01

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:

{% tab caption %}

which, when building a webpage from an .md file, should convert into:

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

where X is the counting number of each particular {% tab caption %} tag in the document; caption is the value for a key from a predefined hash, where the key matches the caption in the tag.

Say, I have the following code in .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; 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!

CodePudding user response:

In Liquid, you can create a for-loop by using the following syntax:

{% for variable in collection %}
  <!-- code to be executed for each iteration -->
{% endfor %}

Here, variable is a variable that will be assigned the value of each item in the collection on each iteration of the loop. The code between the for and endfor tags will be executed for each item in the collection.

For example, to create a for-loop that outputs a list of items in an array:

{% for item in array %}
  <li>{{ item }}</li>
{% endfor %}

This code will output an HTML list with one list item for each item in the array collection.

CodePudding user response:

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)
  • Related