简体   繁体   English

如何将视图加载到变量中?

[英]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.我需要使用 websockets 发送视图,以便可以在选项卡中加载它。 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.似乎加载视图的唯一方法是调用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.大多数模板引擎可以将模板呈现为内存中的字符串,然后您可以将其作为原始数据通过 web 套接字发送。 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 :以下是使用 EJS的方法:

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

While Peter's solution would work for Jade, I am using EJS.虽然彼得的解决方案适用于 Jade,但我使用的是 EJS。 And EJS does not have a renderFile function.而且EJS没有renderFile function。 So here's a generic way to read the a plain HTML file:因此,这是读取普通 HTML 文件的通用方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM