ejs模板的客户端和服务器端渲染 [英] Client side and Server side rendering of ejs template

查看:99
本文介绍了ejs模板的客户端和服务器端渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想学习NodeJS,以便能够在服务器端和客户端运行相同的代码。
我正在将NodeJS与Express和EJS一起使用。
所以。我有一个.ejs页面,其中包含许多HTML,JS,CSS和少量模板。为了公正起见,让它像这样:

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

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.

所以。
现在我要在客户端上重新渲染它。我提出了一些ajax请求,现在the_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?

推荐答案

<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>

从最新版本下载ejs.js或ejs.min.js

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

这篇关于ejs模板的客户端和服务器端渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆