In Express.js, how can I render a Jade partial-view without a “response” object?

北慕城南 提交于 2019-11-30 12:54:35

问题


Using Express.js, I'd like to render a partial-view from a Jade template to a variable.

Usually, you render a partial-view directly to the response object:

response.partial('templatePath', {a:1, b:2, c:3})

However, since I'm inside a Socket.io server event, I don't have the "response" object.

Is there an elegant way to render a Jade partial-view to a variable without using the response object?


回答1:


You can manually compile the Jade template.

var jade = require('jade');
var template = require('fs').readFileSync(pathToTemplate, 'utf8');
var jadeFn = jade.compile(template, { filename: pathToTemplate, pretty: true });
var renderedTemplate = jadeFn({data: 1, hello: 'world'});



回答2:


Here's the straight solution to this problem for express 3 users (which should be widely spread now):

res.partial() has been removed but you can always use app.render() using the callback function, if the response object is not part of the current context like in Liors case:

app.render('templatePath', {
  a: 1,
  b: 2,
  c: 3
},function(err,html) {
  console.log('html',html);
  // your handling of the rendered html output goes here
});

Since app.render() is a function of the express app object it's naturally aware of the configured template engine and other settings. It behaves the same way as the specific res.render() on app.get() or other express request events.

See also:

  • http://expressjs.com/api.html#app.render for app.render()
  • https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x for express 2.x > 3.x migration purposes


来源:https://stackoverflow.com/questions/8644580/in-express-js-how-can-i-render-a-jade-partial-view-without-a-response-object

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