我正在学习javascript作为服务器端语言和函数式语言的新用法。前几天我听说了node.js和express framework。然后我看到了underscore.js作为一组实用函数。我在stackoverflow上看到了这个问题 . 它说我们可以使用underscore.js作为模板引擎。有人知道关于如何使用underscore.js来做模板的教程吗,特别是对于那些对高级javascript缺乏经验的大程序员。谢谢
当前回答
你需要知道的关于下划线模板的一切都在这里。只需要记住3件事:
<% %> -执行一些代码 <%= %> -打印模板中的某些值 <%- %> -打印HTML转义的一些值
就是这样。
简单的例子:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
那么tpl({foo: "blahblah"})将被渲染为字符串<h1>一些文本:blahblah</h1>
其他回答
你需要知道的关于下划线模板的一切都在这里。只需要记住3件事:
<% %> -执行一些代码 <%= %> -打印模板中的某些值 <%- %> -打印HTML转义的一些值
就是这样。
简单的例子:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
那么tpl({foo: "blahblah"})将被渲染为字符串<h1>一些文本:blahblah</h1>
最简单的形式是这样的:
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>');
我想分享一个更重要的发现。
使用<%= variable =>会导致跨站脚本漏洞。所以使用<%- variable ->更安全。
我们必须将<%=替换为<%-以防止跨站点脚本攻击。不确定,这是否会对性能有影响
<!-- 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>
谢谢@ phhearst ! JsFiddle(最新) JsFiddle列表分组的第一个字母(复杂的例子w/图像,函数调用,子模板)分叉!玩得开心点…… @tarun_telang注意到XSS黑客的JsFiddle演示 一种做子模板的非标准方法
Lodash也是一样的 首先编写如下脚本:
<script type="text/template" id="genTable">
<table cellspacing='0' cellpadding='0' border='1'>
<tr>
<% for(var prop in users[0]){%>
<th><%= prop %> </th>
<% }%>
</tr>
<%_.forEach(users, function(user) { %>
<tr>
<% for(var prop in user){%>
<td><%= user[prop] %> </td>
<% }%>
</tr>
<%})%>
</table>
现在编写一些简单的JS,如下所示:
var arrOfObjects = [];
for (var s = 0; s < 10; s++) {
var simpleObject = {};
simpleObject.Name = "Name_" + s;
simpleObject.Address = "Address_" + s;
arrOfObjects[s] = simpleObject;
}
var theObject = { 'users': arrOfObjects }
var compiled = _.template($("#genTable").text());
var sigma = compiled({ 'users': myArr });
$(sigma).appendTo("#popup");
popoup是你想要生成表格的div
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Ubuntu上安装Node.js
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 使用express.js代理
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout