首页 文章

在erb模板中嵌入ejs模板

提问于
浏览
5

我正在构建一个javascript-heavy rails 3应用程序 . 它使用underscore.js,它有一个非常优雅的模板机制, Build 在ejs(http://embeddedjs.com/)之上 .

问题:embeddedjs大量借用erb语法,因此在erb模板中包含ejs模板会导致视图出现渲染问题 .

有没有办法在erb文件中包含“非erb”部分?这将让我在erb文件中定义ejs模板 . 现在我正在使用一个hack,我有一个帮助程序,它读取包含ejs模板的文件的原始内容,并将其输出为erb模板中的原始字符串 .

3 回答

  • 2

    我用这个技巧来解决问题:

    // Using custom tags to be able to use regular for templates in templates
    var ejs = require('ejs');
    ejs.open = '{{';
    ejs.close = '}}';
    
    // Using html extension for custom ejs tags
    app.register('.html', ejs);
    
    app.set('views', __dirname + '/views');
    app.set('view engine', 'html');
    

    这会将<%%>更改为{{}},让我将<%%>用于JS使用的模板 . 这对我有用,因为我没有经典样式模板(<%%>) .

    如果你有很多那些你可能想要做同样的技巧,但对于underscore.js模板 .

  • 3

    您可以将ejs保存为单独的文件,而不是将其作为文本(不会被评估为erb)呈现在脚本标记内 .

    在你的部分内部:

    <script id="my_awesome_template" type="text/x-ejs">
      <%= render :text => File.open("app/views/controller_name/_my_awesome_template.html.ejs").read %>
    </script>`
    

    在您的JavaScript文件中:

    new EJS({element: document.getElementById('my_awesome_template')}).render(data)
    
  • 2

    转义你的下划线变量:(你不想要插入的那些)

    <%= foo %> becomes:
    
    <%%= foo %>
    

相关问题