Embedding an ejs template inside of an erb template

折月煮酒 提交于 2019-12-09 06:27:25

问题


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" sections 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.


回答1:


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.




回答2:


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)



回答3:


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

<%= foo %> becomes:

<%%= foo %>


来源:https://stackoverflow.com/questions/4716557/embedding-an-ejs-template-inside-of-an-erb-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!