TWIG, dynamic associative array key - twig

I need to create a array with a dynamic key.
Example:
{% set key = 'a' %}
{% set value = 'b' %}
{% set array = {key:value} %}

I find a workaround for this problem: if you surround the key with parenthesis the key of array take the value of the variable instead of the name. So try simple this:
{% set array = { (key): value} %}
Here a working solutions

Related

Change value of array element at specific index

I want to change the value of array element at a specific position but whenever i am trying to so it throws me an error. Can anyone suggest me a way to change the value
{% set explode_field_id = data.field_id|split('-') %}
{% set explode_field_id_length = explode_field_id|length %}
{% set reqValue = explode_field_id_length - 1 %}
{% set explode_field_id[reqValue] = data.field_details[dependent_field] %}
{% set dependent_field_id = explode_field_id|join('-') %}
Here explode_field_id = categoryList-category_list-0-category_list
ERROR - Unexpected token "punctuation" of value "[" ("end of statement block" expected).

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] }}

Create a random string in twig with prefix?

Im trying to create a random string with twig with a set prefix eg myPrefix123. The following simply returns myPrefix:
{% set randomID = 'myPrefix'|format(random(1000)) %}
{% set randomID = 'myPrefix' ~ random(1000) %}

Twig: wrap variable in array if not already one, use empty array if missing

I have a variable modifier passed to a few twig templates. I want to be able to not pass it at all, to pass a single string, or to pass an array of strings. I then want to be able to assume it is always an array of strings (possibly empty) in my template code.
At the moment I have at the start of the twig templates
{% set modifier = modifier | default([]) %}
{% if modifier is not iterable %}
{% set modifier = [modifier] %}
{% endif %}
This does what I want, but is there an easier way? It's a lot of code to do something very simple.
You could one-line it with a filter (can't seem to be able to mimic the default filter though)
<?php
$filter = new Twig_SimpleFilter('wrap_array', function ($value) {
return is_array($value) ? $value : [ $value, ];
});
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
And use it in your template :
{% set foo = foo|default({})|wrap_array %}

Resources