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
Related
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
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(' ') }}
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] }}
How is it possible in twig to format a number, without rounding off the decimals?
For example, if the user inputs
12345.35, output should be 12,345.35
12345.356, output should be 12,345.356
12345.3567, output should be 12,345.3567
I tried number_format filter but the first parameter is precision to which the decimals should be rounded to. If I use 12345.35|number_format(4, '.', ',') the result is 12,345.3500 which is not the desired output.
You should determine the number of decimals you have in the number before formatting it. Not quite obvious but I don't find another solution.
Try with this macro:
{% macro show_number(n) %}
{%- spaceless %}
{% set decimals = n | split('.')[1] | default('') | length %}
{{ n | number_format(decimals, '.', ',') }}
{% endspaceless -%}
{% endmacro %}
Runnable example here
Using twig, how can I translate all items in an array and join them with a slash?
Do I have to use an additional variable or is there a cleverer method?
For the moment, I'm doing something like this:
{% set labels = [] %}
{% for feature in menu_item.features %}
{% set labels = labels|merge([feature|trans([], 'features')]) %}
{% endfor %}
{{ labels | join(' / ')}}
It sucks.
Why not just output the content while you're looping ?
{% for feature in menu_item.features %}
{% if loop.index0 > 0 %}/{% endif %}
{{feature|trans}}
{% endfor %}
Maybe I'm late to the party, but you can now do this easily with the map filter:
{{ menu_item.features|map(feature => feature|trans)|join(' / ') }}
See documentation:
Twig >v1.41: https://twig.symfony.com/doc/1.x/filters/map.html
Twig >v2.10: https://twig.symfony.com/doc/2.x/filters/map.html
Twig v3.x: https://twig.symfony.com/doc/3.x/filters/map.html
Not everything should be done within the "view".
This type of code is probably much better placed within your controller logic and then passed into the view as the merged+joined result. Because in your example all you're doing is compiling a result which can much more easily be done within code.