how to use both ejs and jade in one nodejs & express project?

女生的网名这么多〃 提交于 2019-12-12 08:09:05

问题


I want to use ejs for partials and use jade for individual pages, how to use both in one nodejs & express project?


回答1:


It 's easy to find the way in expressjs api docs and consolidate.js at github

Reference the express.js doc fragment below, please


app.engine(ext, callback)

Register the given template engine callback as ext By default will require() the engine based on the file extension. For example if you try to render a "foo.jade" file Express will invoke the following internally, and cache the require() on subsequent calls to increase performance.

app.engine('jade', require('jade').__express);

For engines that do not provide .__express out of the box - or if you wish to "map" a different extension to the template engine you may use this method. For example mapping the EJS template engine to ".html" files:

app.engine('html', require('ejs').renderFile);

In this case EJS provides a .renderFile() method with the same signature that Express expects: (path, options, callback), though note that it aliases this method as ejs.__express internally so if you're using ".ejs" extensions you dont need to do anything.

Some template engines do not follow this convention, the consolidate.js library was created to map all of node's popular template engines to follow this convention, thus allowing them to work seemlessly within Express.

var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);



回答2:


This works for my:

  1. add pug and ejs as renders

index.js

const express = require('express');
const path = require('path');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('view engine', 'ejs');
  1. call render with a filename.fileext.

routes/users

const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
  res.render('users.ejs');
});
module.exports = router;

routes/about

const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
  res.render('about.pug');
});
module.exports = router;


来源:https://stackoverflow.com/questions/16783413/how-to-use-both-ejs-and-jade-in-one-nodejs-express-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!