在hogan-express node.js表达应用程序中,如何在特定路由中使用与全局模板不同的模板?

时间:2014-04-22 08:37:07

标签: node.js express backend hogan.js templating-engine

好的,所以我是表达,模板和后端的新手。我一整天都在搜索这个问题无济于事。所以,我想我会在这里问。

如何在hogan-expressnode.jsexpress应用程序中为除声明的全局模板以外的特定路由使用不同的模板?我仍然想使用partials,所以如果你指的是尝试不同的框架或其他东西,请记住这一点。 (不知道有多常见的偏见...)

守则

以下是我从文档本身查看Hogan-express的代码(它已经从coffescript转换为常规javascript。)

var express = require('express');

var app = express();

// start example code from docs.  
// I use code like this in my app.js/server.js file

app.set('view engine', 'html');

app.set('layout', 'layout'); // the global template as I explained above.

app.set('partials', {
  foo: 'foo'
});

app.enable('view cache');

app.engine('html', require('hogan-express'));

// I have this function referenced from a different file...
// in my code I'll explain below.

app.get('/', function(req, res) {
  res.locals = {
    name: 'Andrew'
  };
  return res.render('template', {
    partials: {
      message: 'message'
    }
  });
});

我的代码如下所示

// in---file---> 'app.js'

var routes = require('./routes/index.js');

app.get('/', routes.index);

// ---in---file---> '/routes/index.js'

exports.index =  function(req,res){

    var template_data = {
        posts : blogposts, 
        currentUser : req.user
    };

    res.render('index.html', template_data);  
};

1 个答案:

答案 0 :(得分:0)

您只需将layout:'layout2'添加到您作为第二个参数发送到res.render的template_data对象中。

// in---file---> 'app.js'

var routes = require('./routes/index.js');

app.get('/', routes.index);

// ---in---file---> '/routes/index.js'

exports.index =  function(req,res){

    var template_data = {
        layout:'layout2', // this is the important addition.
        posts : blogposts, 
        currentUser : req.user
    };

    res.render('index.html', template_data);  
};

新布局适用于您声明的每个路径,但不会覆盖未以此方式声明的其他路线的全局模板。

相关问题