Quiero activar el contenido de todos los atributos en un elemento personalizado <my-component> . Actualmente, solo se ejecuta el atributo anterior.
Si funciona, será <p>hello, world! welcom </p> .
Además, quiero que la parte {{ }} se ejecute con o sin espacios.
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>Debe mover su this.outerHTML = optionsreturn; fuera del ciclo forEach .
También cambié la cadena a una expresión regular en su llamada .replace() . Ahora aceptará cero o un espacio alrededor de los nombres de sus atributos.
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>