I want to fire the contents of all attributes in a custom element <my-component> . Currently, only the preceding attribute is executed.
If it works, this will be <p>hello, world! welcom </p> .
Also, I want the {{ }} part to be executed with or without spaces.
function component(elementName, ComponentOptions) {
customElements.define(`${elementName}`, class extends HTMLElement {
connectedCallback() {
if (ComponentOptions.return) {
if (this.getAttributeNames()) {
const AttrNames = this.getAttributeNames();
var optionsreturn = ComponentOptions.return;
AttrNames.forEach(attr => {
let val = this.getAttribute(attr);
optionsreturn = optionsreturn.replace(`{{ ${attr} }}`, val);
this.outerHTML = optionsreturn;
});
} else {
this.outerHTML = ComponentOptions.return
}
}
}
});
}
component("my-component", {
return: `<p>hello, {{ w }} {{ wel }} </p>`
})
<my-component w="world!" wel="welcom"></my-component>
You need to move your this.outerHTML = optionsreturn; outside the forEach loop.
I also changed the string into a regular expression in your .replace() call. It will now accept zero or one spaces surrounding your attribute names.
function component(elementName, ComponentOptions) {
customElements.define(elementName, class extends HTMLElement {
connectedCallback() {
if (ComponentOptions.return) {
if (this.getAttributeNames()) {
const AttrNames = this.getAttributeNames();
var optionsreturn = ComponentOptions.return;
AttrNames.forEach(attr => {
let val = this.getAttribute(attr);
optionsreturn = optionsreturn.replace(new RegExp(`\{\{ ?${attr} ?\}\}`,"g"), val);
});
this.outerHTML = optionsreturn;
} else {
this.outerHTML = ComponentOptions.return
}
}
}
});
}
component("my-component", {
return: `<p>hello, {{ w }} {{wel}} </p>`
})
<my-component w="world!" wel="welcom"></my-component>