如何在Node.js和Express中以嵌套形式呈现多个.ejs文件?

时间:2013-06-09 21:30:57

标签: node.js express rendering ejs

如何以嵌套形式呈现多个.ejs文件?

所以我有以下文件:

var mysql = require('mysql');
var ejs = require('ejs');
exports.index = function(req, res){
    if (req.method=='POST'){
        var connection = mysql.createConnection({user:'root', password:'root', database:'testdb'});
        var name = req.param('name');
        connection.query('select * from table_name where name = ?', name, function(err, rows, fields){
            if(err) throw err;
            res.render('index', {
                 title: 'title', content: res.render('index2', {data:rows})
            });
        });
    }
});

其中index.ejs由非常基本的html标记(例如html,head,body和一个p标记)组成,并且其中包含<%- content %>,其中假定内容由另一个.ejs文件,它不包含html,head或body标签,仅假定为内容和标题。但是,当我通过POST请求访问此文件并尝试呈现文件然后从我的浏览器检出输出的HTML文件时,内容仅由index2.ejs文件组成,这意味着它没有html,正文,头部标签

那我错过了什么?如果我想通过<script src='some_file.js'></script>包含一个Javascript库,当我尝试在index2.ejs文件中渲染时,我应该添加另一个渲染属性吗?对吗?

3 个答案:

答案 0 :(得分:12)

首先,我认为您对res.render的运作方式感到困惑。根据{{​​3}}:

  

res.render(查看,[本地人],回调)

     

使用回放的字符串呈现回调视图。

解释了为什么您只在HTML页面中看到index2.ejs的内容。


现在,有多种方法可以实现您的目标,即在视图中嵌套视图。从Express 3.x开始,您需要使用include。在这种情况下,您可以像这样重写您的视图:
1-定义header.ejs文件,该文件看起来像docs 2-定义footer.ejs。看起来像这个example 3-在index2.ejs中,包括这两个文件,如下所示:

<% include header %>
    //The HTML of your index2.ejs
    //You can add some reusable views, like, say, a submit button above the footer
    <% include reusable_views/submit %>
<% include footer %>

第二种方法是使用example,它允许您通过仅指定其路径来插入任何视图:

res.render('index', {
                 title: 'title', 
                 content: 'index2', 
                 data:rows
            });

并且,在index1.ejs中,您将拥有:

<html><head>
<title><%= title %></title></head>
<body><p>
<%- partial('index2',{}) %>
</p></body></html>

此方法的优点是您可以使用额外对象将额外值传递给视图。查看ejs-locals github页面了解更多详情。

答案 1 :(得分:3)

答案 2 :(得分:1)

适用于标准HTML,例如headfootersidebars或其他任何内容。 有Partials示例解释了所有内容..