Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Array to string conversion

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

the array is made in PHP through this format:

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

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

    <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

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.

like image 464
Chris98 Avatar asked Sep 17 '15 15:09

Chris98


4 Answers

info is an array, so you should simple write

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

to display your info array.

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

like image 174
JL M Avatar answered Oct 11 '22 01:10

JL M


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:

{% for status in status_info %}
    <a href="{{ status.link }}" title="{{ status.title }}">{{ status.display }}</a>
    {% if not loop.last %}|{% endif %}
{% endfor %}
like image 40
deceze Avatar answered Oct 11 '22 03:10

deceze


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

    {{ array|json_encode(constant('JSON_PRETTY_PRINT')) }} 
    
like image 12
Developer Avatar answered Oct 11 '22 02:10

Developer


if need associative array:

{{info|json_encode(constant('JSON_PRETTY_PRINT'))|raw}}
like image 1
Georg Avatar answered Oct 11 '22 03:10

Georg