@aaashur/eleventy-plugin-create-element
v0.1.1
Published
An Eleventy paired shortcode for building HTML elements, with support for dynamic tag names and attributes
Downloads
3
Maintainers
Readme
eleventy-plugin-create-element
An Eleventy paired shortcode for building HTML elements, with support for dynamic tag names and attributes.
Inspired by
React.createElement()
Setup
Run the following command at the root of your Eleventy project
npm install @aaashur/eleventy-plugin-create-element
then include it in your .eleventy.js
config file:
const createElement = require("@aaashur/eleventy-plugin-create-element");
module.exports = (eleventyConfig) => {
eleventyConfig.addPlugin(createElement);
};
Usage
{% createElement <name>, [<attributes>] %}
<innerHTML>
{% endcreateElement %}
Attributes with null
or undefined
values are omitted:
{% createElement "article", {
class: "card",
href: undefined,
"data-example": null,
"aria-hidden": false
} %}
<p>Hello, world.</p>
{% endcreateElement %}
<article class="card" aria-hidden="false">
<p>Hello, world.</p>
</article>
If attributes
contains a class
property whose value is an array, classnames
will be used automatically to return a space-delimited string containing only truthy, non-duplicate values:
{% createElement "div", {
class: [
"block",
"block__element",
"block__element--modifier" if false,
"block"
]
} %}
<p>Hello, world.</p>
{% endcreateElement %}
<div class="block block__element">
<p>Hello, world.</p>
</div>
If attributes
contains a style
property whose value is an object, styles
will be used automatically to return a semicolon-delimited string containing only truthy values:
{% createElement "div", {
style: {
"--custom-property": "10px",
"--false-property": false,
"--null-property": null,
"--undefined-property": undefined,
"background-color": "red"
}
} %}
<p>Hello, world.</p>
{% endcreateElement %}
<div style="--custom-property: 10px; background-color: red"></div>
<p>Hello, world.</p>
</div>
Empty elements will build self-closing tags automatically:
{% createElement "input", { type: "button" } %}
<p>innerHTML is ignored when building empty elements</p>
{% endcreateElement %}
<input type="button">
If name
is undefined, createElement
will return innerHTML
only:
{% createElement "a" if link, { href: link } -%}
<p>Hello, world</p>
{%- endcreateElement %}
<p>Hello, world</p>