使用Twig在JSON对象数组中按id查找对象

时间:2017-06-04 08:33:56

标签: json symfony twig

我正在传递一个阵列,遗憾的是我无法进行重组:

"options": [
            {"name":"namea","text":"valuea"},
            {"name":"nameb","text":"valueb"},
            {"name":"namec","text":"valuec"},
            {"name":"named","text":"valued"}
           ]

我需要能够找到名称等于namea,nameb,namec等的对象,然后生成相应的文本。我尝试了以下几个其他变体,但无法使其工作:

{% for item in event.options %} 
    {% if item.name == "nameb" %}
        {{ item.text|capitalize }}
    {% endif %}
{% endfor %}

提前感谢您的帮助。

编辑:我基本上只能访问一个文本框来输入HTML和Twig。我无权访问框架,自定义扩展等。

编辑:具有确切格式的JSON:

{
"source": "TEST.COM",
"trigger": "test",
"options": [{
            "name":"test_date",
            "value":"31-05-2017"
            },
            {
            "name":"test_number",
            "value":"9081003"
            },
            {
            "name":"test_test",
            "value":"9asd003"
            },
            {
            "name":"Name",
            "value":"Todd"
            },
            {
            "name":"test_other",
            "value":"kslkjsfd"
            },
            {
            "name":"test_help",
            "value":"908sdf3"
            }]
}

1 个答案:

答案 0 :(得分:0)

无论哪种方式都会非常hacky(我觉得评论中提到的javascript方式仍然不那么hacky)。

然而,由于它的多线程,我们可以编写一个类似于事物的基本解析器(这绝不是防弹,如果内容有“或结构发生变化或任何变化,那么就会失败):

{# create an array of lines #}
{% set event = event|split('\n') %}

{# an array to hold our options #}
{% set options = [] %}

{# using a bool to track if we are inside the options part #}
{% set inOptions = false %}

{# this holds the name of the last name value we have passed #}
{% set currentKey = '' %}

{# go through each line #}
{% for line in event %}

    {# if we are inside the options tag do our magic #}
    {% if inOptions %}
        {# check if the line starts with "name": and track the current key name #}
        {# or check if it starts with "value": and set the current key to that value #}
        {% if line matches '/"name":/' %}
            {# split line on the double quotes and get the last bit #}
            {% set currentKey = line|split('"') %}
            {# cant get the array index piped in one go idk.. #}
            {% set currentKey = currentKey[3] %}
        {% elseif line matches '/"value":/i' %}
            {% set currentValue = line|split('"') %}
            {% set options = options|merge({(currentKey): currentValue[3]}) %}
        {% elseif line matches '/\s*}]/' %}
            {% set inOptions = false %}
        {% endif %}
    {% endif %}

    {# check for the options sectioning start #}
    {% if line matches '/^"options/' %}
        {% set inOptions = true %}
    {% endif %}
{% endfor %}

{{ dump(options) }}

这会在我的转储中返回(你没有,所以你看不到):

array:6 [▼
  "test_date" => "31-05-2017"
  "test_number" => "9081003"
  "test_test" => "9asd003"
  "Name" => "Todd"
  "test_other" => "kslkjsfd"
  "test_help" => "908sdf3"
]

作为一个实际的数组,你可以调用options.test_date,但所有这些都是超级hacky,它仍然可以改进,但是没有为它制作twig,语法变得如此笨重,难以维护。