How to add attribute to element in twig before render?
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 }}