php Twig 数组到字符串的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32633853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:05:29  来源:igfitidea点击:

Twig Array to string conversion

phparraysstringfor-looptwig

提问by Chris98

This is probably relatively easy to do, but I'm new to twig and I'm frustrated.

这可能相对容易做到,但我是树枝的新手,我很沮丧。

I'm adapting code from this answer: https://stackoverflow.com/a/24058447

我正在改编这个答案的代码:https: //stackoverflow.com/a/24058447

the array is made in PHP through this format:

该数组是通过这种格式在 PHP 中制作的:

$link[] = array(
       'link' => 'http://example.org',
       'title' => 'Link Title',
       'display' => 'Text to display',
);

Then through twig, I add html to it, before imploding:

然后通过树枝,我在爆炸之前向它添加 html:

    <ul class="conr">
        <li><span>{{ lang_common['Topic searches'] }} 
        {% set info = [] %}
        {% for status in status_info %}
            {% set info = info|merge(['<a href="{{ status[\'link\'] }}" title="{{ status[\'title\'] }}">{{ status[\'display\'] }}</a>']) %}
        {% endfor %}

        {{ [info]|join(' | ') }}
    </ul>

But I'm getting:

但我得到:

Errno [8] Array to string conversion in F:\localhost\www\twig\include\lib\Twig\Extension\Core.php on line 832

Errno [8] 832 行 F:\localhost\www\twig\include\lib\Twig\Extension\Core.php 中的数组到字符串的转换

It's fixed when I remove this line, but does not display:

删除此行时已修复,但不显示:

{{ [info]|join(' | ') }}

Any ideas how I can implode this properly?

有什么想法可以正确地内爆吗?

** update **

** 更新 **

Using Twig's dump function it returns nothing. It seems it's not even loading it into the array in the first place. How can I load info into a new array.

使用 Twig 的转储函数,它什么都不返回。似乎它甚至没有首先将它加载到数组中。如何将信息加载到新数组中。

采纳答案by deceze

You shouldn't really be building complex data structures inside of Twig templates. You can achieve the desired result in a more idiomatic and readable way like this:

你真的不应该在 Twig 模板中构建复杂的数据结构。您可以像这样以更惯用和可读的方式实现所需的结果:

{% for status in status_info %}
    <a href="{{ status.link }}" title="{{ status.title }}">{{ status.display }}</a>
    {% if not loop.last %}|{% endif %}
{% endfor %}

回答by JL M

info is an array, so you should simple write

info 是一个数组,所以你应该简单地写

{{ info|join(', ') }}

to display your info array.

显示您的信息数组。

[info] is a array with one value : the array info.

[info] 是一个具有一个值的数组:数组信息。

回答by Developer

You can user json_encode for serialize array as strig, then show pretty - build in twig

您可以使用 json_encode 将数组序列化为 srig,然后显示漂亮 - 在树枝中构建

    {{ array|json_encode(constant('JSON_PRETTY_PRINT')) }}