我正在尝试学习javascript作为服务器端语言和函数式语言的新用法。几天前,我听说了node.js和express框架。然后,我将underscore.js看作是一组实用函数。我看到this question on stackoverflow 了。它说我们可以使用underscore.js作为模板引擎。任何人都知道如何使用underscore.js进行模板的好教程,特别是对于没有高级javascript经验的大块头。谢谢
发布于 2011-08-30 18:21:55
你需要知道的关于下划线模板的一切都是here。只需要记住3件事:
<% %> -执行一些code<%= %> -在template<%- %>中打印一些值-打印一些值HTML转义仅此而已。
简单的例子:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");然后,将向字符串<h1>Some text: blahblah</h1>呈现tpl({foo: "blahblah"})
发布于 2012-05-01 04:02:17
<!-- Install jQuery and underscore -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<!-- Create your template -->
<script type="foo/bar" id='usageList'>
<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>
<!-- Create your target -->
<div id="target"></div>
<!-- Write some code to fetch the data and apply template -->
<script type="text/javascript">
var items = [
{name:"Alexander", interests:"creating large empires"},
{name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"},
{name:"..."},
{name:"Yolando", interests:"working out"},
{name:"Zachary", interests:"picking flowers for Angela"}
];
var template = $("#usageList").html();
$("#target").html(_.template(template,{items:items}));
</script>演示,这是一个做@tarun_telang的非标准方法
发布于 2011-08-31 22:35:39
在它最简单的形式中,您可以这样使用它:
var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>' 如果你打算多次使用一个模板,你会想要编译它,这样它会更快:
var template = _.template('<li><%= name %></li>');
var html = [];
for (var key in names) {
html += template({ name: names[i] });
}
console.log(html.join('')); //Outputs a string of <li> items我个人更喜欢Mustache风格的语法。您可以调整模板标记以使用双花括号:
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
var template = _.template('<li>{{ name }}</li>');https://stackoverflow.com/questions/4778881
复制相似问题