Asked  7 Months ago    Answers:  5   Viewed   29 times

How can I set member of an already existing array from Twig?

I tried doing it next way:

{% set arr['element'] = 'value' %}

but I got the following error:

Unexpected token "punctuation" of value "[" ("end of statement block" expected) in ...

 Answers

12

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'}) %}
Wednesday, March 31, 2021
 
makadev
answered 7 Months ago
98

You can first cast the object to array. You can build own filter casting your object to array. More about filters is available here: http://twig.sensiolabs.org/doc/advanced.html#filters

It could then look like that:

{% for key, value in my_object|cast_to_array %}
Wednesday, March 31, 2021
 
ManojGeek
answered 7 Months ago
49

Turns out I was wrong.

You can use the _context variable which contains all variables passed to the template.

Try {{ dump(_context) }}

Relevant Documentation

You can create a function that gets passed this context and the array key to access that value.

This twig function should work fine:

public function getAttribute($context, $key)
{
    if (!array_key_exists($key, $context)) {
        return '';
    }

    return $context[$key];
}

With the variables being passed title=foo and another variable being passed refTitle=title, this should output "foo".

{{ attribute(_context, refTitle) }}
Wednesday, March 31, 2021
 
dmp
answered 7 Months ago
dmp
50

Even if i don't know anything about the application that you are building, i can tell you that it is a bad practice to use hard coded array keys, especially inside a template.

You should not give a whole array to a template if you only need one item. Remember that the template is only the view not your program-logic.

Wednesday, March 31, 2021
 
pamelus
answered 7 Months ago
86

When using a class method as a callback for functions like array_map() and usort(), you have to send the callback as two-value array. The 2nd value is always the name of the method as a string. The 1st value is the context (class name or object)

// Static outside of class context
array_map( array( 'ClassName', 'methodName' ), $array );

// Static inside class context
array_map( array( __CLASS__, 'methodName' ), $array );

// Non-static outside of object context
array_map( array( $object, 'methodName' ), $array );

// Non-static inside of object context
array_map( array( $this, 'methodName' ), $array );
Wednesday, August 18, 2021
 
Cam1989
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :