How do I escape EJS template code in node.js to be evaluated on the client side?

删除回忆录丶 提交于 2019-12-06 06:08:13

The way I have dealt with this is to override the opening and closing tags on node so that the 2 instances of ejs are lookgin for different tags.

On node you can pass in options

{open:'<%',close:'%>'}

In my case I use <% and <@ for my two versions. Then in node ejs template I have something like this (where name is from backbone and everyauth obviously from node):

<% if(everyauth.loggedIn) %><h1><@= name @></h1><% } %>

Well, the way that I currently approach this is to use require.js with the text plugin; this allows me to include the templates using AJAX during development time and have them all compiled into an optimized/minified single file bundle during deploy time.

Of course, if you don't use require.js for dependency management of the rest of your JS code this doesn't work nearly as well, but I can't stand to do javascript dev without require.js anymore now that I'm used to it anyway.

Alternately, there may be other similar technologies that you could use to solve the same problem.

user1603813

I use backbone.layout.manager on both the client and server side, because I want my templates to be exactly the same.

The way I solved the template delimiter issue was to render the page on the server side, then inject the raw backbone templates.

With new ejs you can add a custom delimiter at client side :

https://github.com/mde/ejs#custom-delimiters

eg :

Custom delimiters can be applied on a per-template basis, or globally:

var ejs = require('ejs'),
    users = ['geddy', 'neil', 'alex'];

// Just one template
ejs.render('<?= users.join(" | "); ?>', {users: users}, {delimiter: '?'});
// => 'geddy | neil | alex'

// Or globally
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
// => 'geddy | neil | alex'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!