【问题标题】:How do I load a view into a variable?如何将视图加载到变量中?
【发布时间】:2011-09-28 06:31:47
【问题描述】:

我需要使用 websockets 来发送视图,以便可以在选项卡中加载它。但我似乎无法弄清楚如何将视图加载到变量中以进行发送。似乎加载视图的唯一方法是调用 response.render() 函数。

有什么想法吗?

【问题讨论】:

    标签: javascript view node.js express


    【解决方案1】:

    大多数模板引擎可以将模板呈现为内存中的字符串,然后您可以通过 Web 套接字将其作为原始数据发送。这是来自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
    });
    

    如果您具体提到您使用的是哪个模板引擎,我们可以根据需要给出具体示例。

    这里是how to do it with EJS

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

    【讨论】:

    • 使用ejs,ejs中是否有类似的renderFile方法?
    • 用一些 EJS 细节更新了我的答案。 (可能有不止 1 个名为 EJS 的项目...)
    【解决方案2】:

    虽然 Peter 的解决方案适用于 Jade,但我正在使用 EJS。而且 EJS 没有 renderFile 函数。因此,这是读取纯 HTML 文件的通用方法:

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

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多