简体   繁体   中英

Escape <%- %> tag in underscore.js template

I'm using underscore.js for templating. In my project, I'm using it on the server (with Node.js) to fill in a couple of values. I also have a template embedded in a tag on the page that I want to fill in multiple times using data downloaded with AJAX.

Basically, in the tag, I have something like this:

<script>
    var UserID = '<%= userID %>';
</script>

which I want to be filled in before the page is sent out.

Then, I have something like this:

<script type='template' id='my_template'>
    <li><%- item %></li>
</script>

Which I want to remain in that form to be used by the script on my page.

Of course, you may have figured out by now that when I render the page on the server, it complains that item is undefined. Is there any way to escape those tags, so underscore will ignore it and just send it out as-is? I know I could define different tag delimiters for one of them but it seems simpler and cleaner to use a consistant format.

You can use _.template settings:

_.template( templateString, data, {
    escape: false, // use a false evaluated value
    evaluate: /(.)^/ // or a not matching regex
});

Also see related sections in anonated source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM