Client side and Server side rendering of ejs template

Amantel picture Amantel · Dec 6, 2016 · Viewed 9.7k times · Source

I always wanted to learn NodeJS to be able to run the same code on server and client side. I am using NodeJS with Express and EJS. So. I have a .ejs page with lot's of HTML, JS, CSS and a small bit with template. For the sake of justice let it be like this:

the_list-->some.ejs

<ul> 
<% for(i=0;i>the_list.length;i++) { %>
    <li>the_list[i]</li>
<% } %>
</ul>    

After some rendering on the server we have a perfect list.

So. Now I want to rerender it on the client. I made some ajax request and now I have new items in the_list. What is the right way?

Answer

Sagi_Avinash_Varma picture Sagi_Avinash_Varma · Dec 6, 2016

As per ejs templates documentation

var template = new EJS({
  text: `
    <ul>
      <% for(i = 0; i < the_list.length; i++) { %>
        <li>the_list[i]</li>
      <% } %>
    </ul>
  `
});
var html = template.render({ the_list: data });
document.getElementById('list-wrapper').innerHTML = html;