The attrs() function in Twig gives you access to a powerful utility class called HtmlAttributes, which provides a
fluent, expressive, and safe way to manipulate HTML attributes directly within your templates.
This function returns a HtmlAttributes object that can be chained to construct complex attribute sets — with full
support for conditional logic, class and style manipulation, JSON serialization, and more.
You can also conditionally set a value, which is very useful so you don’t have to wrap your statements into {% if
statements:
attrs().set('disabled', true, isDisabled) {# Only if isDisabled is true #}attrs().setIfExists('title', maybeTitle) {# Only sets if maybeTitle is truthy #}
Examples
What about a dynamic button?
<button{{attrs().addClass(['btn','btn-primary']).set('disabled',true,notisActive).set('type','submit')}}>
Save
</button>