Embedding an ejs template inside of an erb template

戏子无情 提交于 2019-12-03 09:06:22

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