DoraCMS

您现在的位置是:首页>文档内容页

文档详情

第9天response 响应渲染 —动态渲染实例

doramart 2015-10-19 14:29:21 NodeJs224828
首先,我们建立一个views目录,用来储存动态模板文件,里面建立两个文件index.html和about.html

动态渲染实例

首先,我们建立一个views目录,用来储存动态模板文件,里面建立两个文件index.htmlabout.html

index.html

<!doctype html>
<html>
    <head>
        <title><%=locals.title%></title>
    </head>
    <body>
        hello:<%=locals.name%>
    </body>
</html>

bookabout.htmlbook

<!doctype html>
<html>
    <head>
        <title>locals.title</title>
    </head>
    <body>
        <p>About me:</p>
        <table border=1>
        <% locals.info.forEach(function(r){%>
            <tr>
                <td><%=r[0]%></td>
                <td><%=r[1]%></td>
            </tr>
        <% }) %>
        </table>
    </body>
</html>

run.js运行文件

var fk = require("../..")
   ,App = fk.App
   ,download = fk.download
   ,app = new App
   ,view = fk.view
   ,fs = require("fs");

   app.use(view(__dirname+"/views"));

   app.get("/",function(req,res){

       res.view("index.html",{title:"index page",name:"leo"});
   })

   app.get("/about",function(req,res){
       var info = [
          ["Name","Leo"],
          ["Tel","213442322"],
          ["Card","322232"]
       ]
       res.view('about.html',{title:"about me info",info:info});
   })

   app.listen(3000);

当启动 node run 后,在浏览器中输入 http://localhost:3000  会显示index.html模板+数据的页面。下面是浏览器显示的html源代码:

<!doctype html>
<html>
    <head>
        <title>index page</title>
    </head>
    <body>
        hello:leo
    </body>
</html>

当输入 http://localhost:3000/about  时,浏览器页面的html源代码如下:

<!doctype html>
<html>
    <head>
        <title>locals.title</title>
    </head>
    <body>
        <p>About me:</p>
        <table border=1>

            <tr>
                <td>Name</td>
                <td>Leo</td>
            </tr>

            <tr>
                <td>Tel</td>
                <td>213442322</td>
            </tr>

            <tr>
                <td>Card</td>
                <td>322232</td>
            </tr>

        </table>
    </body>
</html>

通过这个实例,我们知道了动态模板渲染的重要性,想象一下如果web框架没有这个功能,那还能用它做什么呢。明天是stuwebfk框架开发的最后一天,让stuwebfk具有session会话特性。

文章评论

取消回复
登录 参与评论

评论列表(