Setting Element of Array from Twig

Setting element of array from Twig

There is no nice way to do this in Twig. It is, however, possible by using the merge filter:

{% set arr = arr|merge({'element': 'value'}) %}

If element is a variable, surround it with brackets:

{% set arr = arr|merge({(element): 'value'}) %}

PHP - Twig change array key value

In twig, always keep everything simple, without hard logic.

In your case, just create 3 variables.

{% set amount_under_10, amount_between_10_and_20, amount_over_20 = 0,0,0 %}

{% for invoice in invoices %}
<tr>
<td>{% if invoice.age <= 10 %}{% set amount_under_10 = amount_under_10 + 1 %}{% endif %}{{ invoice.age }}</td>
<td>{% if invoice.age > 10 and invoice.age <= 20 %}{% set amount_between_10_and_20 = amount_between_10_and_20 + 1 %}{% endif %}{{ invoice.age }}</td>
<td>{% if invoice.age > 20 %}{% set amount_over_20 = amount_over_20 + 1 %}{% endif %}{{ invoice.age }}</td>
</tr>
{% endfor %}

{{ amount_under_10 }}
{{ amount_between_10_and_20 }}
{{ amount_over_20 }}

See fiddle

If you need to be more generic (arbitrary number of ranges for example) don't do it in Twig. Twig is made for rendering information, no more.

TWIG, dynamic associative array key

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

How to set multi-dimensional array in Twig?

In Twig, arrays are marked with [], and hashes with {}. A hash is a key-value pair with explicit keys (strings or integers), an array is simply a set of values without any explicitly defined keys (they will be indexed numerically).

In order to use a hash, you MUST provide a key for each element.

So, what you want is probably {% set fields = [ {'name': 'description', 'value': '1'}, { 'name': 'abc', 'value': '2'}, { 'name':'tags', 'value': '3'} ] %}

How to set array value in twig template

what about,

{% set params = params|merge({'redirect_uri': 'http://site.loc/'}) %}

Reorganize array in twig

First a FYI though, this is not something you should be doing in the template, cause the code is pretty messy. Anyway here is how you merge/group arrays in twig:

{% set output = [] %}
{% for item in items %}
{% if not attribute(output, item.object.category) is defined %}
{% set output = output|merge({ (item.object.category) : {}, }) %}
{% endif %}

{% set output = output|merge({(item.object.category) : output[item.object.category] | merge([ item, ]) }) %}
{% endfor %}

{% for category, items in output %}
{{ category }}:
{% for item in items %}
{{ item.object.name }}
{% endfor %}
{% endfor %}

demo

related problem

issues with merge in twig

Twig: Add item to array from within an included template

This can't be done in Twig, as seen in the compiled source of the templates each included templats get his own private scope as the context array is based by value and not by reference

$this->loadTemplate("bar.twig", "main.twig", 2)->display($context);

which then calls doDisplay in the included template

protected function doDisplay(array $context, array $blocks = array())

note

You could alter this behaviour by creating your own Twig_Environment and Twig_Template but a quick look shows me that there are quite some functions you'd need to override.


main.twig

{% set foo = 'bar' %}
{% include 'bar.twig' %}

Foo in foo: {{ foo }}

bar.twig

{% set foo = 'foo' %}
Foo in bar: {{ foo }}

Source main.twig


/* main.twig */
class __TwigTemplate_4ba23e628289532331bb5889dca1a4ec57774924d21a760ca6fe6f575a3978b5 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);

$this->parent = false;

$this->blocks = array(
);
}

protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["foo"] = "bar";
// line 2
$this->loadTemplate("bar.twig", "main.twig", 2)->display($context);
// line 3
echo "
Foo in foo: ";
// line 4
echo twig_escape_filter($this->env, ($context["foo"] ?? null), "html", null, true);
}

public function getTemplateName()
{
return "main.twig";
}

public function isTraitable()
{
return false;
}

public function getDebugInfo()
{
return array ( 26 => 4, 23 => 3, 21 => 2, 19 => 1,);
}

public function getSourceContext()
{
return new Twig_Source("", "main.twig", "/fuz/twigfiddle.com/files/environment/k85WDdymIFgSoXLc/twig/main.twig");
}
}

Source bar.twig

<?php

/* bar.twig */
class __TwigTemplate_16789decfbb837d4631acf2e648380c0658722c50a0b53184b3f3c5f68f9b0ae extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);

$this->parent = false;

$this->blocks = array(
);
}

protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["foo"] = "foo";
// line 2
echo "Foo in bar: ";
echo twig_escape_filter($this->env, ($context["foo"] ?? null), "html", null, true);
}

public function getTemplateName()
{
return "bar.twig";
}

public function isTraitable()
{
return false;
}

public function getDebugInfo()
{
return array ( 21 => 2, 19 => 1,);
}

public function getSourceContext()
{
return new Twig_Source("", "bar.twig", "/fuz/twigfiddle.com/files/environment/k85WDdymIFgSoXLc/twig/bar.twig");
}
}


Related Topics



Leave a reply



Submit