Add an attr
function to make outputting HTML attributes easier
#3930
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Here is a quick PoC for #3907.
First, it adds a
attr_merge
filter. This filter is intended to be used with arrays that represent HTML attribute name-value pairs. Basically, it works like|merge
, but for the special key namesclass
,style
anddata
it performs merging on thevalue
level.This is intended for the use case where you'd like to add to the attributes for an HTML element based on conditions, e. g. multiple subsequent
{% if ... %}
blocks.Example:
{ class: 'foo' }|attr_merge({ class: 'bar' })
will be{ class: ['foo', 'bar'] }
{ class: 'foo' }|attr_merge({ class: ['bar', 'baz'] })
will be{ class: ['foo', 'bar', 'baz'] }
{ class: { special: 'foo' } }|attr_merge({ class: ['bar', 'baz'] })|attr_merge({ class: {special: 'qux' } })
will be{ class: { special: 'qux', 0: 'bar', 1: 'baz' } }
or in Twig code:
Second, it adds a
attr
function. This function takes one or multipleattr
arrays like above, and print them as a series of HTML attribute markup. All values fromclass
will be concatenated with spaces. Key/value pairs fromstyle
will be treated as CSS property/value pairs. Fordata
, keys will be used to constructdata-{keyname}
attributes.Example:
will generate HTML markup:
TODO: