javascript - 如何在 Express 中使用 Underscore 模板代替 Jade?

标签 javascript node.js express underscore.js pug

我不想使用 Express 默认附带的 Jade 模板引擎。我尝试按照本指南进行操作,但失败了:

http://blog.luksidadi.com/expressjs-underscore-template/

有问题的错误是:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: callback function required
    at Function.engine (/home/me/blog/node_modules/express/lib/application.js:173:38)
    at Object.<anonymous> (/home/tk/blog/app.js:28:5)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

当我尝试启动服务器时,我得到了这个:

node app.js

如何解决?

app.js:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  //app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

// Add these lines to register underscore template
var _ = require('underscore');
app.engine('.html', {
  compile: function(str, options){
    var compiled = require('underscore').template(str);
    return function(locals) {
        return compiled(locals);
    };
  }
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

routes/index.js:

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index.html', { title: 'Express' });
};

layout.html:

< html >
  < head >
    < title ><%=title%>< /title >
  < /head >
  < body >
  <%=body%>
  < /body >
< /html >

index.html:

Hello world

最佳答案

使用consolidate.js将 Underscore 的模板函数转换为接受 Express 在 3.x 中要求的格式 (path[, locals], callback)

关于javascript - 如何在 Express 中使用 Underscore 模板代替 Jade?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14906846/

相关文章:

javascript - 在Node.js中,如何以不同的频率更新页面的不同组件?

javascript - 随机化对象并将其拆分为 2 个数组

javascript - jquery 绑定(bind)事件不会在手机上触发

javascript - 根据Rails 3中另一个collection_select中的选定项目自动填充text_fields

javascript - 使用通配符比较nodeJS对象

node.js - HTTP GET 参数未传递给 Express app.get

javascript - 如何在我所有的请求查询字符串中包含 JSON webtoken

javascript - 如何将全局变量传递给 util 函数

javascript - 如何正确使用 nconf 和熨斗

javascript - 如何使用 MongoDB/Nodejs 和 Express 检索基于 JavaScript 的游戏的保存数据?