HyderA
HyderA

Reputation: 21371

How do I load a view into a variable?

I need to use websockets to send a view so it can be loaded within a tab. But I can't seem to figure out how to load view into a variable for sending. Seems like the only way to load a view is to call the response.render() function.

Any ideas?

Upvotes: 0

Views: 555

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 145994

Most templating engines can render a template to an in-memory string, which you can then send over your web socket as raw data. Here's the example from jade.

var jade = require('jade');

// Render a string
jade.render('string of jade', { options: 'here' });

// Render a file
jade.renderFile('path/to/some.jade', { options: 'here' }, function(err, html){
    // options are optional,
    // the callback can be the second arg
});

If you mention specifically which templating engine you are using, we can give specific examples if needed.

Here's how to do it with EJS:

html = new EJS({url: '/template.ejs'}).render(data)

Upvotes: 2

HyderA
HyderA

Reputation: 21371

While Peter's solution would work for Jade, I am using EJS. And EJS does not have a renderFile function. So here's a generic way to read the a plain HTML file:

s.readFile(__dirname + '/views/tabs/' + data.tab + '/index.ejs', 'utf8', function( err, html )
{
    socket.emit( 'setTabHTML', { tab: data.tab, 'html': html });
});

Upvotes: 1

Related Questions