Array to string conversion, with split - twig

I have a text like: 000325175
and I want to format it as: 000 325 175.
Nothing's easier (in theory) with the split filter, as:
{{ mynumber|split('', 3) }}
But I get a
An exception has been thrown during the rendering of a template ("Notice: Array to string conversion")
However I can apply a slice filter without any problem.
{{ mynumber|slice(9, 14) }}
So I don't understand. Thanks for help

The split filter return an array (with the spitted values), you should only iterate over the result to display it as follow:
{% for partial in mynumber|split('', 3) %}
{{ partial}}
{% endfor %}
Here a working solutions
EDIT:
You can also use the join filter and concatenate the results as example:
{{ mynumber|split('', 3)|join(' ') }}

Related

Problem creating JSON outuput in Twig Template

I'm learning to use the Craft CMS, which uses Twig templating. I'm trying to output a JSON object in Twig, but instead of 2 items in the JSON I'm getting info about a single item.
Here is my code:
{% set newsitems = craft.entries.section('newsitems').orderBy('PostDate desc').limit(100) %}
{% set response = [] %}
{% for newsitem in newsitems %}
{{ 'Here' }}
{% set response = response|merge({'type':0, 'id':newsitem.id, 'link':newsitem.sourceLink}) %}
{% endfor %}
{{ response|json_encode() }}
And here is the output I get:
Here Here {"type":0,"id":"25","link":"https:\/\/gadgets.ndtv.com"}
As can be seen, the loop executes two times ('Here' is printed 2 times) but there is only one item in the JSON array which is printed.
Am I missing something basic? Any help would be appreciated. Thanks in advance.
Twig's merge filter uses array_merge in the background.
The manual states the following
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
This is what is happening to your output, in the first iteration you've create an associative array with the key: type, id, link. In the x'th iteration you are just overwriting the values stored in said keys. The solution is also stated in the manual, numeric indices will be appended to the array instead of overwriting it.
In twig you would solve it as this:
{% set response = [] %}
{% for newsitem in newsitems %}
{% set response = response|merge([{ 'type': 0, 'id': newsitem.id, 'source': newsitem.source,},]) %}
{% endfor %}
{{ response|json_encode|raw }}
demo

how to use split twig template field content type in drupal 8?

I need your help to solve the problem with split in twig.
I want to separate my var {{label}} in an array,
try using
{% set array = label | split (" ")%}
returns empty
I want to separate a field node in an array,
try using
{% set array = content.field_fieldname | split (" ")%}
returns empty
if someone helps me identify what I'm doing wrong, or I indicates a guide and / or tutorial that can solve my problem. Thanks
How do you check that the array is empty?
{% set label = 'this is a label'%}
{% set array = label | split (" ")%}
{% for elem in array %}
{{loop.index}} - {{ elem}}
{% endfor %}
Check this code online here
{{ label }} is in the template as an object, I solved get the string
{% set title = items[0]['content']['#context']["value"]|split(' ', 2) %}
<h1>{{ title[0] }}</h1>
{{ title[1] }}

Twig translate dynamic value/string from database

Explanation:
I pull these values from my local database and try to display them on the front-end. The issue is, that I have 2 languages that I need to cater to.
Example:
{% if activeLocale == "si" %}
{{ record.estate_type_SI|raw }}
{% elseif activeLocale == "en" %}
{{ record.estate_type_EN|raw }}
{% endif %}
This works, but when I have multiple items it gets gruesome because I have to write everything down two times. What this does is that depending on the language a value from a different column in the database is pulled.
I am wondering if I can do something similar to this:
{{ record.estate_type_{{"SI"|trans}}|raw }}
I will gladly buy you a beer if you can help me out with this.
Cheers!
EDIT: Variables
Using attribute , you can access a property of an object in a dynamic way. Then you just have to use upper filter to match what you need.
{{ attribute(record, 'estate_type_'~ activeLocale|upper)|raw }}

How in twig to set 2 dimentional array in macros

How in twig to set 2 dimentional array in macros and to run it?
I did :
{{ components.menu_item( "Hostels", 'hostel', {'admin/hostel/index': 'All Hostels'}, {'admin/hostel/active_featured_listings': 'Active Featured Hostels'} ) }}
{% macro menu_item(title, active_admin_link, items_array) %}
title::{{ title }}<br>
items_array::{{ dump(items_array) }}<br>
{% endmacro %} {# menu_item END #}
But only 1st array elemented was outputted
array (size=1) 'admin/hostel/index' => string 'All Hostels' (length=11)
What is rigth way and how make for circle?
Thanks!
From the Twig doc:
["foo", "bar"]: Arrays are defined by a sequence of expressions
separated by a comma (,) and wrapped with squared brackets ([]).
So try surround the input with squared brackets, as follow:
{{ components.menu_item( "Hostels", 'hostel', [{'admin/hostel/index': 'All Hostels'}, {'admin/hostel/active_featured_listings': 'Active Featured Hostels'}] ) }}
Hope this help

Twig Access Array Index?

Is it possible to directly access an array index from within a Twig template?
Here's my setup, using Silex:
return $app['twig']->render('template', array('numbers' => array('one', 'two', 'three')));
so can I do something like this?
{{numbers[0]}}
Just before posting this I realized, that's exactly what you can do, but as I didn't find the answer anywhere in the docs or google (correct me if I'm wrong), I've posted this anyway.
{{numbers[0]}}
The answer of Adam, is correct, only to make it clear and improve,
you can have access directly to array index
{{ myArray[0] }}
if you need to access in a loop
{% set arrayOfItems = ['ZERO', 'ONE'] %}
{% set myArray = ['APPLE', 'ORANGE'] %}
{% for oneItem in arrayOfItems %}
<p>{{ oneItem }} equals {{ myArray[loop.index0] }}</p>
{% endfor %}
in this example I used an array inside a non related loop so the result is:
ZERO equals APPLE
ONE equals ORANGE
Thats actually something what doesnt work for me when using Twig with shopware 6.
I try to access an object like
{{ page.cart.lineItems.elements[0].quantity }}
what will lead into a parsing error of the Twig Template
I can use
{{ page.cart.lineItems.elements | first }}
to get the first Element, but dont know how i can then access a property of this first element

Resources