Insert ejs template inside erb template

I am creating javascript-heavy rails 3 applications. It uses underscore.js, which has a very elegant template engine built on top of ejs ( http://embeddedjs.com/ ).

Problem: embeddedjs is highly dependent on erb syntax, so including ejs in the erb template causes presentation problems.

Is there a way to include non-erb sections in an erb file? This would allow me to define ejs patterns inside erb files. Right now I am using a hack where I have an assistant that reads the raw contents of a file containing ejs templates and displays this as an raw string in an erb template.

+5
source share
3 answers

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 allows me to use <%%> for templates that are used by JS. This works for me as I don't have classic style templates (<%%>).

If you have many of these, you might want to do the same trick, but for underscore.js templates.

+3
source

You can save ejs as a separate file and make it as text (which will not be evaluated as erb) inside the script tag.

Inside the erb particle:

<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)
+2
source

: (, , erb )

<%= foo %> becomes:

<%%= foo %>
+2

All Articles