Javascript 如何使用 underscore.js 作为模板引擎?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4778881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use underscore.js as a template engine?
提问by knodumi
I'm trying to learn about new usages of javascript as a serverside language and as a functional language. Few days ago I heard about node.js and express framework. Then I saw about underscore.js as a set of utility functions. I saw this question on stackoverflow . It says we can use underscore.js as a template engine. anybody know good tutorials about how to use underscore.js for templating, especially for biginners who have less experience with advanced javascript. Thanks
我正在尝试了解 javascript 作为服务器端语言和功能语言的新用法。几天前我听说了 node.js 和 express 框架。然后我看到 underscore.js 是一组实用函数。我在 stackoverflow 上看到了这个问题 。它说我们可以使用 underscore.js 作为模板引擎。任何人都知道如何使用 underscore.js 进行模板制作的好教程,尤其是对于高级 javascript 经验较少的大人物。谢谢
回答by SET
Everything you need to know about underscore template is here. Only 3 things to keep in mind:
您需要了解的有关下划线模板的所有信息都在这里。只需要记住3件事:
<% %>
- to execute some code<%= %>
- to print some value in template<%- %>
- to print some values HTML escaped
<% %>
- 执行一些代码<%= %>
- 在模板中打印一些值<%- %>
- 打印一些 HTML 转义的值
That's all about it.
这就是全部。
Simple example:
简单的例子:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
then tpl({foo: "blahblah"})
would be rendered to the string <h1>Some text: blahblah</h1>
然后tpl({foo: "blahblah"})
将被渲染到字符串<h1>Some text: blahblah</h1>
回答by Shanimal
<!-- 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>
回答by evilcelery
In it's simplest form you would use it like:
以最简单的形式,您可以像这样使用它:
var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'
If you're going to be using a template a few times you'll want to compile it so it's faster:
如果您打算多次使用模板,则需要对其进行编译以使其更快:
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
I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:
我个人更喜欢 Mustache 风格的语法。您可以调整模板标记标记以使用双花括号:
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
var template = _.template('<li>{{ name }}</li>');
回答by inf3rno
The documentation for templating is partial, I watched the source.
模板的文档是部分的,我看了源。
The _.templatefunction has 3 arguments:
该_.template函数有3个参数:
- String text: the template string
- Object data: the evaluation data
- Object settings: local settings, the _.templateSettingsis the global settings object
- String text: 模板字符串
- 对象数据:评价数据
- 对象设置:本地设置,_.templateSettings是全局设置对象
If no data(or null) given, than a renderfunction will be returned. It has 1 argument:
如果没有给出数据(或空值),则将返回渲染函数。它有 1 个参数:
- Object data: same as the dataabove
- 对象数据:与上面的数据相同
There are 3 regex patterns and 1 static parameter in the settings:
设置中有 3 个正则表达式模式和 1 个静态参数:
- RegExp evaluate: "<%code%>" in template string
- RegExp interpolate: "<%=code%>" in template string
- RegExp escape: "<%-code%>"
- String variable: optional, the name of the dataparameter in the template string
- RegExp评估:模板字符串中的“<%code%>”
- RegExp插值:模板字符串中的“<%=code%>”
- 正则表达式转义:“<%-code%>”
- 字符串变量:可选,模板字符串中数据参数的名称
The code in an evaluatesection will be simply evaluated. You can add string from this section with the __p+="mystring"command to the evaluated template, but this is not recommended (not part of the templating interface), use the interpolate section instead of that. This type of section is for adding blocks like if or for to the template.
评估部分中的代码将被简单评估。您可以使用__p+="mystring"命令将此部分中的字符串添加到评估模板中,但不建议这样做(不是模板界面的一部分),请使用 interpolate 部分而不是。这种类型的部分用于将 if 或 for 之类的块添加到模板中。
The result of the code in the interpolatesection will added to the evaluated template. If null given back, then empty string will added.
插值部分中的代码结果将添加到评估模板中。如果返回 null,则将添加空字符串。
The escapesection escapes html with _.escapeon the return value of the given code. So its similar than an _.escape(code)in an interpolatesection, but it escapes with \the whitespace characters like \nbefore it passes the code to the _.escape. I don't know why is that important, it's in the code, but it works well with the interpolateand _.escape- which doesn't escape the white-space characters - too.
该逃逸部分逃脱HTML与_.escape在给定的代码的返回值。因此,它的比类似_.escape(代码)中的内插部分,但它与逃逸\的空白字符等\ n它传递的代码到前_.escape。我不知道为什么那么重要,它在代码中,但它与interpolate和_.escape配合得很好——它也不会转义空白字符。
By default the dataparameter is passed by a with(data){...}statement, but this kind of evaluating is much slower than the evaluating with named variable. So naming the datawith the variableparameter is something good...
默认情况下,数据参数由with(data){...}语句传递,但这种评估比使用命名变量评估要慢得多。所以用可变参数命名数据是件好事......
For example:
例如:
var html = _.template(
"<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" +
"as the \"<%= _.escape(o.text) %>\" and the same<br />" +
"as the \"<%- o.text %>\"</pre>",
{
text: "<b>some text</b> and \n it's a line break"
},
{
variable: "o"
}
);
$("body").html(html);
results
结果
The "<b>some text</b> and
it's a line break" is the same
as the "<b>some text</b> and
it's a line break" and the same
as the "<b>some text</b> and
it's a line break"
You can find here more examples how to use the template and override the default settings: http://underscorejs.org/#template
您可以在此处找到更多示例,说明如何使用模板并覆盖默认设置:http: //underscorejs.org/#template
By template loading you have many options, but at the end you always have to convert the template into string. You can give it as normal string like the example above, or you can load it from a script tag, and use the .html()function of jquery, or you can load it from a separate file with the tpl pluginof require.js.
通过模板加载,您有很多选择,但最后您总是必须将模板转换为字符串。你可以把它作为像例如正常的字符串以上,或者你可以从一个脚本标签加载它,使用的.html()的jQuery的功能,也可以从与一个单独的文件中加载第三方物流插件的require.js.
Another option to build the dom tree with laconicinstead of templating.
使用简洁而不是模板构建 dom 树的另一种选择。
回答by dinesh_malhotra
I am giving a very simple example
我举一个非常简单的例子
1)
1)
var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate);
The result would be
结果是
Welcome you are at mysite.This has been created by john whose age is 25.
2) This is a template
2)这是一个模板
<script type="text/template" id="template_1">
<% _.each(items,function(item,key,arr) { %>
<li>
<span><%= key %></span>
<span><%= item.name %></span>
<span><%= item.type %></span>
</li>
<% }); %>
</script>
This is html
这是 html
<div>
<ul id="list_2"></ul>
</div>
This is the javascript code which contains json object and putting template into html
这是包含 json 对象并将模板放入 html 的 javascript 代码
var items = [
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
}
];
$(document).ready(function(){
var template = $("#template_1").html();
$("#list_2").html(_.template(template,{items:items}));
});
回答by Khalid Ahmada
with express it's so easy. all what you need is to use the consolidatemodule on node so you need to install it :
用快递就这么简单。您所需要的只是在节点上使用consolidate模块,因此您需要安装它:
npm install consolidate --save
then you should change the default engine to html template by this:
那么您应该通过以下方式将默认引擎更改为 html 模板:
app.set('view engine', 'html');
register the underscore template engine for the html extension:
为 html 扩展注册下划线模板引擎:
app.engine('html', require('consolidate').underscore);
it's done !
完成 !
Now for load for example an template called 'index.html':
现在加载一个名为“index.html”的模板:
res.render('index', { title : 'my first page'});
maybe you will need to install the underscore module.
也许您需要安装下划线模块。
npm install underscore --save
I hope this helped you!
我希望这对你有帮助!
回答by Tarun
I wanted to share one more important finding.
我想分享一个更重要的发现。
use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.
使用 <%= variable => 会导致跨站点脚本漏洞。所以使用 <%- variable -> 更安全。
We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance
我们不得不将 <%= 替换为 <%- 以防止跨站点脚本攻击。不确定,这是否会影响性能
回答by Dr.Sai
Lodash is also the same First write a script as follows:
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>
Now write some simple JS as follows:
现在写一些简单的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");
Where popoup is a div where you want to generate the table
popoup 是你想要生成表格的 div