Underscore javascript library to populate a template

I'm using the underscore library to populate my template. It works like a charm when my variable day is inside a tag. like this snippet from my code:

    <template>  
     <label>Schedule</label>
      <select class="form-control" onchange="set_from_hour('<%=day%>')" name="some_name" id="<%=day%>from_hour" >
          <option value=0 selected='selected'>00</option>
          <option value=1>01</option>
           ...
 </template>

to populate this template I use this function:

days_schedule = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']
    function show_schedule_week(){
             _.each(days_schedule,function(day){
                 _.templateSettings.variable = 'day'
                 var template = _.template($('template').html())                                                                                               
                 console.log(day+'_schedule')
                 $('#'+day+'_schedule').prepend(template(day))
             })
         }

Now the problem comes when i want my HTML code to display the variables, say in a header tag the variable day like below:

<template>
<h1> <%- day%> </h1>
</template>

The browser displays

<%- day%>

instead of the value of the variable. Do you know what I'm doing wrong?

Upvotes: 0

Views: 44

Answers (1)

trincot
trincot

Reputation: 351328

The problem is with the string that you pass to _.template(): the HTML that you read from the DOM does not have <%- day%>, but &lt;%- day&gt;. This is because < has a special meaning in HTML, and as here it does not represent a tag, it is encoded with an HTML entity. The same goes for >.

There are several solutions to this. One is to not use a template element in your HTML, but a string literal in your code. If however you prefer to stick with the template element (which is reasonable), then you could turn the template content into an HTML comment.

Here is an example:

days_schedule = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']
function show_schedule_week() {
    _.each(days_schedule,function(day){
        _.templateSettings.variable = 'day'
        // unwrap the template content by removing the HTML comment tag start/end 
        var template = _.template($('template').html().slice(4, -3));                                                                                   
        $('#'+day+'_schedule').prepend(template(day))
    })
}

show_schedule_week();
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.11.0/underscore-min.js" integrity="sha512-wBiNJt1JXeA/ra9F8K2jyO4Bnxr0dRPsy7JaMqSlxqTjUGHe1Z+Fm5HMjCWqkIYvp/oCbdJEivZ5pLvAtK0csQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>

<template><!--
    <h3> <%- day%></h3>
--></template>

<div id="monday_schedule"></div>

Upvotes: 1

Related Questions