How to debug an underscore.js template

Given a simple template like this:

<div class="solution" data-question-id="<%= model.get('Id') %>">    
    <div class="title"><%= model.get('Name') %></div>
    <div class="company"><%= model.get('Company') %></div>
    <div class="version"><%= model.get('Version') %></div>
    <div class="detail"><%= model.get('Summary') %></div>
    <div class="actions">
        <a href="/#solution/<%= Id %>/<%= model.get('Id') %>">Detail</a>

And using your favorite JavaScript interactive debugger (Visual Studio 2012 is my favorite when I’m doing MVC 4 Razor development), just add a debugger statement within your template temporarily:

<div class="solution" data-question-id="<%= model.get('Id') %>">
    <% debugger; %>
    <div class="title"><%= model.get('Name') %></div>

Assuming debugging is enabled, this will break (in Visual Studio for example) on the debugger line whenever your code template is executed.

The emitted template code thankfully has line feeds embedded so it’s readable:

function anonymous(obj,_) {
var __t,__p='',__j=Array.prototype.join,print=function(){,'');};
__p+='<div class="solution" data-question-id="'+
((__t=( model.get('Id') ))==null?'':__t)+
'">\r\n    ';
__p+='\r\n    <div class="title">'+
((__t=( model.get('Name') ))==null?'':__t)+
'</div>\r\n    <div class="company">'+
((__t=( model.get('Company') ))==null?'':__t)+
'</div>\r\n    <div class="version">'+
((__t=( model.get('Version') ))==null?'':__t)+
'</div>\r\n    <div class="detail">'+
((__t=( model.get('Summary') ))==null?'':__t)+
'</div>\r\n    <div class="actions">\r\n        <a href="/#solution/'+
((__t=( Id ))==null?'':__t)+
((__t=( model.get('Id') ))==null?'':__t)+
'">Detail</a>\r\n    </div>\r\n</div>\r\n';
return __p;


You’ll see the debugger emitted in-line. It’s very handy for inspect the values of variables, objects, etc. In the example above, I wanted to confirm that the model being passed was in the proper format.

I’ve used it many times to help debug a template that wasn’t working the way I’d expected.

This also works well in Chrome’s debugger.