posthtml-expressions
posthtml-expressions copied to clipboard
Define new attributes
Currently it is possible to use variables as values of existing attributes, but there is no ability to add new attributes. What if we check here for variables defined as attributes themselves:
<button {{{btnAttrs}}} type="{{ type }}"></button>
and do something like
for (let key in node.attrs) {
if (key.indexOf('{{') === 0) { //just a hack
let newAttrs = placeholders(key, ctx, delimitersSettings); // attributes string
// merge newAttrs with node.attrs and delete node.attrs[key]
} else {
node.attrs[key] = placeholders(node.attrs[key], ctx, delimitersSettings)
}
}
having locals:
locals: {
type: 'submit',
btnAttrs: 'data-num="1" data-txt="txt" data-attr="attr"',
},
What would be even more powerful is the ability to merge existing attributes with new ones, so we can redefine existing attributes along with adding new ones:
<merger MERGE_ME_WITHIN_INCLUDE="data-num='1' data-txt='txt' data-attr='attr'">
<include src="include.html"></include>
</merger>
But I yet can not see how this instruction can be implemented with html syntax (considering that data will be defined in HTML)... Maybe some JS instruction/code within a <script> would fit (though this would be pretty strange thing as a whole), but then it is in conflict with the actual html content, which also may include <script> tags
Probably will be problematic because of whitespace issue: posthtml parser can't recognize such expressions if there is whitespace in them. So {{{btnAttrs}}} is one attribute, but {{{ btnAttrs }}} is multiple attributes. Same goes with tags. It could be an edge case where you not allowed to use whitespace, but this is controversial
Attributes merging turned out to be pretty easy: https://github.com/andreyvolokitin/posthtml-expressions/commit/7be91c59b2d3d84a24fd7f5b4588895cbe6e341c#diff-6d186b954a58d5bb740f73d84fe39073R170
@andreyvolokitin was this merged? How it works?
I used it as a fork, worked fine, shouldn't be hard to make an updated PR