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?
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)
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 });
});
精彩评论