Search code examples
javascriptstringlit-elementlit

lit-element replace string with html tag


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 class="blablaclass" @click = ${() => this.clickfnc()} >
      <div class="blablaclass1">
        ${html`<span> ${this.t('main-text').replace('[0]', this.renderCardText )} </span>`}
      </div>
      <div> 
        <img class="blablaclass2" 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 

Solution

  • 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 class="blablaclass" @click = ${() => this.clickfnc()} >
            <div class="blablaclass1">
              ${html`<span>${before}${html`<strong>${this.t('bold-text')}</strong>`}${after}</span>`}
            </div>
            <div> 
            <img class="blablaclass2" 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 class="blablaclass" @click = ${() => this.clickfnc()} >
            <div class="blablaclass1">
              ${html`<span>${unsafeHTML(this.t('main-text').replace('[0]', `<strong>${this.t('bold-text')}</strong>`))}</span>`}
            </div>
            <div> 
            <img class="blablaclass2" src="./resources/right-arrow.svg"/>
            </div>
          </div>
        </section>`;
    }
    

    Make sure you trust the string you put in there.