循环遍历嵌套的JSON元素并查找自定义Jekyll标记的值

时间:2022-11-26 08:16:03

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

我正在编写一个自定义的Jekyll标记,它接受两个变量(文本和语言)并将文本转换为提供的语言选项。

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

例如,{%localize next de%}应返回“Weiter”,给定此localization.json文件:

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

The plugin code is in Ruby:

插件代码在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.

直到@word,它很好但是每当我有这个嵌套数组时我都无法遍历它,所以#{@ record}目前没有返回任何内容。由于我不了解Ruby,@ word.each部分的语法可能不正确。

1 个解决方案

#1


2  

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.

在你的例子中,你继续循环直到最后一个没有键“de”的翻译(“ko”),你最终得到一个空结果。

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

#1


2  

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.

在你的例子中,你继续循环直到最后一个没有键“de”的翻译(“ko”),你最终得到一个空结果。

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