#Twig

Articles

Tips

Merge twig attributes with object

To change multiple parts of an Attributes object in twig, merge it with an object keyed with updated attributes.

Use the output to create a new attributes object and overwrite the attributes variable.

Switch statement in twig

You may want to transform a value in a twig template.

You can do that by checking a condition on the value in an if, and provide values in the then/else.

{% set newvalue = value == 'asdf' ? '123': '456' %}

If you have different inputs and outputs, you can create a switch like this.

{% set title_color = {green: 'text-green-3', yellow: 'text-yellow-2', blue: 'text-grey-2'}[color] %}

This defines an object, then uses the input value to retrieve the mapped result.