Search code examples
javascripthtmlunderscore.jstemplate-engine

Avoid global variable on underscorejs


I'm with a problem when using underscorejs. It's not beeing possible render the template correctly. Looks like the variable passed need to be global, but is it really true? I would like to avoid this. I'm getting this error: Uncaught ReferenceError: items is not defined. If I use items instead of var items, the things work. But I would like to avoid this. How can I fix it?

This code was adapted from this question.

index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Title</title>

        <script data-main="index" src="require.min.js"></script>
    </head>
<body>
<script id='template' type="text/x-underscore">
<table cellspacing='0' cellpadding='0' border='1' >
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <%
        // repeat items 
        _.each(items,function(item,key,list){
          // create variables
          var f = item.name.split("").shift().toLowerCase();
      %>
        <tr>
          <!-- use variables -->
          <td><%= key %></td>
          <td class="<%= f %>">
            <!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
            <h3><%- item.name %></h3>
            <p><%- item.interests %></p>
          </td>
        </tr>
      <%
        });
      %>
    </tbody>
  </table>
</script>

<div id="target"></div>
</body>
</html>

index.js:

var application = {
    initialize: function() {
      this.load();
    },
    jsPool: [
     'jquery-1.11.2.min.js',
     'underscore-min.js',
    ],
    load: function() {
      define(
        this.jsPool,
        this.onReady
      );
    },
    onReady: function() {
      render();
    }
};

application.initialize();

function render() {
  var items = [
      {name:"Alexander"},
      {name:"Barklay"},
      {name:"Chester"},
      {name:"Domingo"},
      {name:"Edward"},
      {name:"..."},
      {name:"Yolando"},
      {name:"Zachary"}
  ];

  var template = $("#template").html();
  $("#target").html(_.template(template,{items:items}));
}

Solution

  • My read of the _.template() API is that it returns a function which you execute by invoking it with your data elements. Try _.template(template)({items:items}). A simplified demo is inline.

    var render = function() {
      var items, templateStr, templateFunction, rendered;
      items = [
          {name:"Alexander"},
          {name:"Barklay"},
          {name:"Chester"},
          {name:"Domingo"},
          {name:"Edward"},
          {name:"..."},
          {name:"Yolando"},
          {name:"Zachary"}
      ];
    
      templateStr = $("#template").html();
      templateFunction = _.template(templateStr);
      rendered = templateFunction({myItems:items});
      $("#target").html(rendered);
    }
    
    render();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
    
    <script id='template' type="text/x-underscore">
    <% _.each(myItems, function(item, key, list) { %>
    <p>item.name: <%= item.name %></p>
    <% }); %>
    </script>
    
    <div id="target"></div>