Embedding an ejs template inside of an erb template

后端 未结 3 1432
天涯浪人
天涯浪人 2021-02-10 06:48

I\'m building a javascript-heavy rails 3 app. It uses underscore.js, which has a very elegant templating mechanism built on top of ejs ( http://embeddedjs.com/).

The pr

相关标签:
3条回答
  • 2021-02-10 07:32

    You could save ejs as a seperate file and than render it as a text (which won't be evaluated as erb) inside script tag.

    Inside your erb partial:

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

    In your JavaScript file:

    new EJS({element: document.getElementById('my_awesome_template')}).render(data)
    
    0 讨论(0)
  • 2021-02-10 07:40

    Escape your Underscore variables: (The ones you do not want erb to interpolate)

    <%= foo %> becomes:
    
    <%%= foo %>
    
    0 讨论(0)
  • 2021-02-10 07:42

    I use this trick to solve the problem:

    // 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');
    

    This changes <% %> to {{ }}, and let me use <% %> for templates which are used by JS. This works for me as I don't have classic style templates (<% %>).

    If you have a lot of those you may want to do the same trick but for underscore.js templates.

    0 讨论(0)
提交回复
热议问题