Home > Mobile >  lit-element replace string with html tag
lit-element replace string with html tag

Time:09-30

I have a lit element based javascript project, when I want to throw an html tag with .replace in a text, I encounter either the value with the tag or a structure in the form of object, object, I made a structure as follows, what am I doing wrong? basicly my values

main-text = abc dcf [0] xyz
bold-text = 123 

and my render here

render() { return html`
 <section >
  <div  @click = ${() => this.clickfnc()} >
      <div >
        ${html`<span> ${this.t('main-text').replace('[0]', this.renderCardText )} </span>`}
      </div>
      <div> 
        <img  src="./resources/right-arrow.svg"/>
      </div>
  </div>
</section>`; 

}
get renderCardText(){
    return html`<strong>this.t('bold-text')</strong>`;
}

and outputs

output: acv dcf [] xyz 
without call html in function just return output: acv dcf <strong>123</strong> xyz 

CodePudding user response:

The html tag function returns a TemplateResult object so you can't use it as a replacement in String.prototype.replace().

There are a couple different options for what you want to do:

  1. Split the string instead of replacing and combine them piece by piece.
render() {
  const [before, after] = this.t('main-text').split('[0]'); 
  return html`
    <section >
      <div  @click = ${() => this.clickfnc()} >
        <div >
          ${html`<span>${before}${html`<strong>${this.t('bold-text')}</strong>`}${after}</span>`}
        </div>
        <div> 
        <img  src="./resources/right-arrow.svg"/>
        </div>
      </div>
    </section>`;
}

This can get tricky if you have more than 1 things to replace.

  1. Replace as string and use the unsafeHTML directive.
render() {
  return html`
    <section >
      <div  @click = ${() => this.clickfnc()} >
        <div >
          ${html`<span>${unsafeHTML(this.t('main-text').replace('[0]', `<strong>${this.t('bold-text')}</strong>`))}</span>`}
        </div>
        <div> 
        <img  src="./resources/right-arrow.svg"/>
        </div>
      </div>
    </section>`;
}

Make sure you trust the string you put in there.

  • Related