Lior Grossman
Lior Grossman

Reputation: 315

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

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?

Upvotes: 13

Views: 7434

Answers (2)

matthias
matthias

Reputation: 2264

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:

Upvotes: 14

staackuser2
staackuser2

Reputation: 12422

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'});

Upvotes: 13

Related Questions