Search code examples
javascripthtmlbackbone.jsexpressejs

How to keep Express from interpreting a template script tag as actual EJS


I have a simple EJS template in a script tag for use with Backbone.js in my HTML, like this:

<script type="text/template" id="template-wallets">
    <% if(i === 0) {%>
    <div class='wallet-box selected'>
    <% } else {%>
    <div class='wallet-box'>
    <% }%>
    <img src='api/identicon/<%= wallet.get('address') %>'>
    <div class='wallet-label'><%= wallet.get('address').substring(0, 8) %></div>
    </div>
</script>

However, the page this is on is an EJS page itself, served by Express. When the page is requested, Express interprets the contents of the script tag as EJS and tries to render it, and this is problematic for obvious reasons. Is there any way I can escape the EJS in the script tag in such a way that it ends up on the page as-is, ready to be read by JavaScript on the client side?


Solution

  • The simplest way is to change ejs open and close tags. E.g.:

    res.render('backbone-template', { open: '<<', close: '>>' });