2014-12-19 56 views
3

我想在使用node-express服務器託管的HTML文件中使用underscore.js。該文件正用於在客戶端呈現動態數據。下面是代碼:underscore.js與node-express

在app.js:

var cons = require('consolidate'); 
app.engine('html', cons.underscore); 
app.set('view engine', 'html'); 
app.locals._ = require("underscore"); 

在HTML:

var template = _.template($('#client-list-template').html(), {clients: response}); 

這裏 「響應」 是相同的HTML一個JSON

下模板腳本

<script id ="client-list-template", type='text/template'> 
     <table class="table striped"> 
      <thead> 
       <tr> 
        <th>ID</th><th></th> 
       </tr> 
      </thead> 
      <tbody> 
       <% _.each(clients, function(client) { %> 
        <tr> 
         <td><%= client.clientID %></td> 
         <td><a class="btn">Edit</a></td> 
        </tr> 
       <% }); %> 
      </tbody> 
     </table> 
    </script> 

運行此代碼拋出和錯誤:

ReferenceError: clients is not defined

有人可以幫助我瞭解什麼是錯誤以及如何解決它。在Apache服務器中託管的相同HTML工作正常。

+0

你記錄了'response'嗎?它看起來可能是未定義的 –

+2

'_.template'不帶兩個參數。它需要一個(模板)並返回一個函數,該函數本身需要一個參數(數據)。 – Jack

+1

@Jack它確實[有兩個參數](http://underscorejs.org/#template),但第二個不是數據,它是模板字符串的設置。但是,溫尼,你應該做他說的。 – jakerella

回答

1

你試過這種方式嗎?

var template = _.template($('#client-list-template').html()); 
$('.output-div').html(template({ 
    clients : response 
}); 

你怎麼得到響應變量?