Loop through nested JSON elements and find a value for a custom Jekyll tag

599 views Asked by At

I am writing a custom Jekyll tag that takes two variables (text and language) and translates the text to the supplied language option.

For example, {% localize next de %} should return "Weiter", given this localization.json file:

{
    "prev": [{
        "en": "Prev"
    }, {
        "de": "Zurück"
    }, {
        "ko": "이전"
    }],
    "next": [{
        "en": "Next"
    }, {
        "de": "Weiter"
    }, {
        "ko": "다음"
    }]
}

The plugin code is in Ruby:

module Jekyll
   class LocalizeTag < Liquid::Tag

    def initialize(tag_name, variables, tokens)
        super
        @variables = variables.split(" ")
        @string = @variables[0]
        @language = @variables[1]
        @words = JSON.parse(IO.read('localization.json'))
        @word = @words[@string]
        @word.each do |record|
            @record = record[@language]
        end
    end

    def render(context)
        "#{@record}"
    end
  end
end

Liquid::Template.register_tag('localize', Jekyll::LocalizeTag)

Up to @word, it is fine but whenever I have that nested array I cannot loop through it so #{@record} is returning nothing at the moment. As I have no knowledge of Ruby, the syntax for @word.each part may not be correct.

1

There are 1 answers

0
approxiblue On BEST ANSWER

In your example, you keep looping until the last translation ("ko"), which doesn't have the key "de", and you end up with a null result.

You need to stop the loop when you've found the correct translation.

@word.each do |record|
    if record.key?(@language)
        @record = record[@language]
        break
    end
end