Search code examples
javascripthtmlperformancetemplate-engine

Reusing elements in JavaScript templating engines


My question is about how JS templating engines work.

For example, I have template that looks like this:

<div class="my-block"> 
   <h1>{{title}}</h1>
   <p>{{description}}</p>
</div>

... and with data:

{
   title: 'Hello',
   description: 'World'
}

... it renders into DOM element that is saved into some variable (simply by replacing {{title}} and {{description}} with String replace() (something like this):

<div class="my-block"> 
   <h1>Hello</h1>
   <p>World</p>
</div>

Only one element of such type is present at once, but values in it (title and descrition) are changed pretty frequently.

How can I avoid creating DOM element each time (.my-block), and replace {{title}} and {{description}} of existing element automatically?


Solution

  • Add some markup to your code

    <div class="my-block"> 
       <h1 class="slot-a">Hello</h1>
       <p class="slot-b">World</p>
    </div>
    

    Then update it with (using jQuery for simplicity, use whatever you want)

    $('.my-block .slot-a').text(data.title);
    $('.my-block .slot-b').text(data.description);