Client side and Server side rendering of ejs template

后端 未结 3 1348
深忆病人
深忆病人 2020-12-20 02:42

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 HTM

相关标签:
3条回答
  • 2020-12-20 03:25

    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;
    
    0 讨论(0)
  • 2020-12-20 03:33
    <div id="output"></div>
    <script src="/assets/js/ejs.js"></script>
    <script>
      let blogPosts = [
        {
            title: 'Perk is for real!',
            body: '...',
            author: 'Aaron Larner',
            publishedAt: new Date('2016-03-19'),
            createdAt: new Date('2016-03-19')
        },
        {
            title: 'Development continues...',
            body: '...',
            author: 'Aaron Larner',
            publishedAt: new Date('2016-03-18'),
            createdAt: new Date('2016-03-18')
        },
        {
            title: 'Welcome to Perk!',
            body: '...',
            author: 'Aaron Larner',
            publishedAt: new Date('2016-03-17'),
            createdAt: new Date('2016-03-17')
        }
    ];
          var html = ejs.render(`<% for(let i = 0; i < posts.length; i++) { %>
        <article>
            <h2><%= posts[i].title %></h1>
            <p><%= posts[i].body %></p>
        </article>
    <% } %>`, {posts: blogPosts});
      // Vanilla JS:
      document.getElementById('output').innerHTML = html;
    </script>
    

    download ejs.js or ejs.min.js from latest version

    0 讨论(0)
  • 2020-12-20 03:46

    This should work, looks like your problem was the relational operator '>' because it will never output something.

    <ul>
        <% for(var i=0; i<the_list.length; i++) { %>
            <li>
                <a>
                    <%= the_list[i]%>
                </a>
            </li>
        <% } %>
    </ul>
    
    0 讨论(0)
提交回复
热议问题