开发者

Embedding an ejs template inside of an erb template

开发者 https://www.devze.com 2023-02-04 23:17 出处:网络
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/).

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 problem: embeddedjs borrows heavily from the erb syntax, so including ejs templates in an erb template causes rendering problems with the view.

Is there a way to include "non-erb" sec开发者_如何学Ctions in an erb file? This would let me define ejs templates inside erb files. Right now I'm using a hack where I have a helper that reads the raw contents of a file containing ejs templates, and outputting that as a raw string in the erb template.


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.


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)


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

<%= foo %> becomes:

<%%= foo %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号