How to add attribute to element in twig before render? I have a template for one of my forms and I want to add css class to the element before I render it but since I am printing the element as a whole I am not sure how to alter the attributes.

I was told on IRC to have a look at the merge method but so far no luck.

{% set submit_attributes = form.submit.attributes %}
{% submit_attributes.addClass('test') %}
{% form.submit.attributes|merge(submit_attributes) %}
{{ form.submit }}


or

{% form.submit.attributes.addClass('test') %}
{{ form.submit }}
Here is my solution for adding a placeholder to a custom text field being used for inputting search terms in a form.  I could not use element.attributes.setAttributes() because in my case the key for attributes is #attributes.

{% set attr = form.search_api_fulltext['#attributes']|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = form.search_api_fulltext|merge({'#attributes': attr}) %}
{{ search }}


Here is the same expanded a little for clarity:

{% set search = form.search_api_fulltext %}   
{% set attr = form.search_api_fulltext['#attributes'] %}
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %}

{{ search }}


Or add a third merge and merge the field back into the form.  Then output the form as usual:

{% set search = form.search_api_fulltext %}
{% set attr = form.search_api_fulltext['#attributes'] %} 
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %} 

{% set form = form|merge({'search_api_fulltext': search}) %}
{{ form }}