Lit-element, how to concatenate TemplateResult?

1.8k Views Asked by At

We have a custom template element that displays the header-title and we would like to extend this component to also show the header title with breadcrumbs when we have clicked on a button.

Sample code:

      ... private getTemplateResultFromProperty: TemplateResult[] = []; ...
        
            //This works fine: 
            func1(): TemplateResult {
            return html`  
                  <custom-header-template
                    .data=${data}'>
                </custom-header-template>` 
        }


                 //Can't return concatenated header  
                 func2(): TemplateResult {
                //repeat does not work, this returns empty strings
                    return html`${repeat(this.getTemplateResultFromProperty, t => t)}`;
            
                } 

We are able to return and display the new header only in the func2 method by specifying an array element without using the html`` like so: return this.headerTemplateArray[1] But that is not what we would like to do..

Error message: Uncaught (in promise) TypeError: Cannot read property 'split' of null at new Template (template.js:87) when we try this: return html`${this.getTemplateResultFromProperty}`;

The html`` approach does not seem to work for us at all in this method... So we suspect there might be a problem with either the way we use repeat() or that we are concatenate/using TemplateResult in the wrong way.

Any ideas?

illustration

1

There are 1 best solutions below

2
On

lit-html supports rendering arrays of any other renderable value, include TemplateResults. You should just be able to return the array if you don't need to modify it, and it truly is already an array of TemplateResults.

  func2(): Array<TemplateResult> {
    this.getTemplateResultFromProperty;
  } 

If for some reason you need to put this into a single TemplateResult for some other non-lit-html code (I hope that's not the case, if so perhaps you can widen your types), then you can just wrap the array:

  func2(): TemplateResult {
    html`${this.getTemplateResultFromProperty}`;
  } 

If that's not working, then I suspect that getTemplateResultFromProperty is not actually an Array<TemplateResult>. Since it looks like you tried that can you introspect that variable to make sure it's really an array or iterable?