Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 476
Lior Grossman Avatar asked Dec 27 '11 12:12

Lior Grossman


People also ask

What does res render () function do?

The res. render() function is used to render a view and sends the rendered HTML string to the client. Parameters: This function accept two parameters as mentioned above and described below: Locals: It is basically an object whose properties define local variables for the view.

What is partials in Express JS?

Partials are basically just views that are designed to be used from within other views. They are particularly useful for reusing the same markup between different views, layouts, and even other partials. <%- partial('./partials/navbar.ejs') %>


1 Answers

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
like image 77
matthias Avatar answered Sep 28 '22 09:09

matthias