简体   繁体   English

用Liquid计数数组中的项目

[英]Count items in array with Liquid

I have a json object like the following: 我有一个像下面这样的json对象:

    "results"=>{
        "data"=>[
            {
                "id"=>"letters",
                "values"=>["A", "B", "B", "X"]
            },
        ]
    }

I am trying to count how many A 's and how many B 's and then add them. 我试图算出A的个数和B的个数,然后将它们相加。

This is my code so far: 到目前为止,这是我的代码:

require 'liquid'
Liquid::Template.error_mode = :strict
@template = Liquid::Template.parse('
    {% assign letters = results.data | where: "id", "letters" %}
    {{ letters }}
    {% increment a_count %}
    {% increment b_count %}
    {% for letter in letters.values %}
        {% if letter contains "A" %}
            {% increment a_count %}
        {% endif %}
        {% if letter contains "B" %}
            {% increment b_count %}
        {% endif %}
    {% else %}
        The collection is empty.
    {% endfor %}
    {% assign count = a_count | plus: b_count %}
    {{ a_count}} + {{ b_count }} = {{ count }}
')
print(@template.render(
    "results"=> {
        "data"=> [
            {
                "id"=> "letters",
                "values"=> ["A", "B", "B", "X"]
            },
        ]
    }
), { strict_variables: true })
print(@template.errors) 

But this doesn't work and I get this output: 但这不起作用,我得到以下输出:



    {"id"=>"letters", "values"=>["A", "B", "B", "X"]}
    0
    0

        The collection is empty.


    1 + 1 = 2

Which is confusing because results.values is not empty and I only call increment once for each a_count and b_count which should set the initial value to 0 . 这是令人困惑的,因为results.values不为空,并且我只为应将初始值设置为0每个a_countb_count调用一次increment

The output of print(@template.errors) is only: print(@template.errors)的输出仅为:

{:strict_variables=>true}[]

How do I count how many A 's and how many B 's are in the letters.values array? 我如何计算letters.values数组中有多少个A和多少个B

Is it possible for you to combine it with JS? 您可以将其与JS结合吗? You can pass the array to a JS function and do there ther rest. 您可以将数组传递给JS函数,然后再休息。

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

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