user10867452
user10867452

Reputation: 21

How to assign conditional value on twig object

I have a following code and I want to be able to assign value of count conditionally.

{% set obj = {
 count: CONDITIONAL VALUE,
 city: 'London',
 country: 'UK'
} %}

I have an object with many properties, I need to check if that object has property counter . If it has I want to assign value of counter to count above else I want to pass 2 as default value to count. In javascript i could do:- count: counter || 2

Thank you very much

Upvotes: 1

Views: 548

Answers (1)

DarkBee
DarkBee

Reputation: 15641

If you want a default value for a non-existing or null variable u'd use the filter default

{% set obj = {
 count: my_value|default(2),
 city: 'London',
 country: 'UK'
} %}


{{ obj.count }}

demo

Upvotes: 1

Related Questions