2013-05-16 56 views
0

我已經使用了本教程使用下劃線的模板。 http://backbonetutorials.com/what-is-a-view/使用下劃線更新元素

我有一種情況,我只是想在p標籤中添加一些文本到div結構。 這不是一個模板,只是一些需要注入一些值的文本。 有沒有辦法使用下劃線來更新本文中的變量。或者,我需要創建文本作爲模板,然後添加使用HTML模板(_template)

<div id="popup"> 
<p>I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%></p> 
</div> 

UPDATE:

關閉它基於使用此代碼模板文檔我試圖做。

<html> 
<head> 
    <script type="text/javascript" src="js/jquery.min.js"></script> 
    <script type="text/javascript" src="js/underscore.js"></script> 
    <script type="text/javascript" src="js/core.js"></script> 
</head> 
<body> 
    <div id="popup"> 
    <div id="template_holder"></div> 
    </div> 

<!-- TEMPLATES FOR CANCEL PAYMENT MODEL --> 
<script type="text/template" id="card-success_tmp"> 
    <p>I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%></p> 
</script> 
</body> 
</html> 

然後在我的核心js文件我有下面這段代碼,會啓動我的彈出

var variables = {variable1:'[xxxx]', variable2:'[MM/YY]'}; 
var template = _.template($("#card-success_tmp").html(), variables); 
$('#popup #template_holder').html(template); 

click事件裏面,但上面仍然沒有工作。

我甚至試過

var template = _.template($("#card-success_tmp").html()); 
$('#popup #template_holder').html(template({variable1:'[xxxx]', variable2:'[MM/YY]'})); 

它呈現的文本,但該變量傳遞沒有得到呈現。

如果我將模板作爲字符串添加而不是從腳本標記中添加,那麼它將起作用。 問題是爲什麼它不是從腳本標記工作。它呈現文本而不是傳遞給它的變量。

var template = _.template("<p>I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%></p>"); 
$('#popup #template_holder').html(template({variable1:'[xxxx]', variable2:'[MM/YY]'})); 
+0

普通下劃線,還是你有骨幹(包括jQuery)? – Bergi

+0

普通下劃線沒有骨幹 – Chapsterj

+0

但是你有jQuery? – Bergi

回答

1

這不是一個模板只是一些文字,需要有注入到它的一些價值觀。

這使它成爲模板,不是嗎?

隨着Underscore docs提到,您可以預編譯它:

var tmpl = _.template("<p>I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%></p>"); 

// often: 
$("#popup").append(tmpl({variable1: "some text", variable2:"another variable text"})); 

或直接調用它:

$("#popup").append(_.template(
    "<p>I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%></p>", 
    {variable1: "some text", variable2:"another variable text"} 
)); 

您提供的片段:該template_holder div有一個id,不一個類屬性。修復,both ofyour codes工作。

+0

嗨Bergi我已經更新我的問題使用下劃線文檔,但我仍然無法讓它在模板中呈現我的變量。 – Chapsterj

0

我的代碼不工作的原因只是在別人遇到同樣的問題。 我的模板是一個.gsp文件,它是一個grails應用程序文件。所以當它呈現給html時,它會刪除下劃線標籤,因爲grails使用ERB語法來註釋。這裏的關鍵是將ERB語法改爲mustache.js樣式標籤。爲了讓下劃線知道發生了這種變化,您還必須爲下劃線添加一些默認設置。 因此,在您的js文件中,只需在頂部添加此項。

_.templateSettings.interpolate = /\{\{=(.+?)\}\}/g; 
_.templateSettings.evaluate = /\{\{(.+?)\}\}/g; 

然後你的模板代碼可以看起來像這樣。

<script type="text/template" id="card-success_tmp"> 
    <p>I want to add some text in here {{=variable1}}, Then add another variable text in here {{=variable2}}</p> 
</script> 

這是另一個很好的帖子。 Boolean checks in underscore templates