我正在尝试了解 javascript 作为服务器端语言和功能语言的新用法。几天前我听说了 node.js 和 express 框架。然后我看到 underscore.js 是一组实用函数。我在 stackoverflow 上看到了这个问题 。它说我们可以使用 underscore.js 作为模板引擎。任何人都知道关于如何使用 underscore.js 进行模板制作的好教程,尤其是对于高级 javascript 经验较少的大人物。谢谢
如何使用 underscore.js 作为模板引擎?
您需要了解的有关下划线模板的所有信息都在这里。只需要记住3件事:
<% %>- 执行一些代码<%= %>- 在模板中打印一些值<%- %>- 打印一些 HTML 转义值
这就是全部。
简单的例子:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
然后tpl({foo: "blahblah"})将被渲染到字符串<h1>Some text: blahblah</h1>
<!-- 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>
以最简单的形式,您可以像这样使用它:
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>');
模板的文档是部分的,我看了源。
该_.template函数有3个参数:
- String text : 模板字符串
 - 对象数据:评价数据
 - 对象设置:本地设置,_.templateSettings是全局设置对象
 
如果没有给出数据(或空值),则将返回渲染函数。它有 1 个参数:
- 对象数据:相同的数据上述
 
设置中有 3 个正则表达式模式和 1 个静态参数:
- RegExp评估:模板字符串中的“<%code%>”
 - RegExp插值:模板字符串中的“<%=code%>”
 - 正则表达式转义:“<%-code%>”
 - 字符串变量:可选,模板字符串中数据参数的名称
 
评估部分中的代码将被简单评估。您可以使用__p+="mystring"命令将此部分中的字符串添加到评估模板,但不推荐这样做(不是模板界面的一部分),请使用 interpolate 部分而不是。这种类型的部分用于将 if 或 for 之类的块添加到模板中。
插值部分中的代码结果将添加到评估模板中。如果返回 null,则将添加空字符串。
该逃逸部分逃脱HTML与_.escape在给定的代码的返回值。因此,它的比类似_.escape(代码)中的内插部分,但它与逃逸\的空白字符等\ n它传递的代码到前_.escape。我不知道为什么这很重要,它在代码中,但它与interpolate和_.escape配合得很好——它也不会转义空白字符。
默认情况下,数据参数由with(data){...}语句传递,但这种评估比使用命名变量评估要慢得多。所以用可变参数命名数据是件好事......
例如:
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);
结果
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"
您可以在此处找到更多示例如何使用模板并覆盖默认设置:http : //underscorejs.org/#template
通过模板加载,您有很多选择,但最后您总是必须将模板转换为字符串。你可以把它作为像例如正常的字符串以上,或者你可以从一个脚本标签加载它,使用的.html()的jQuery的功能,也可以从与一个单独的文件中加载第三方物流插件的require.js .
使用简洁而不是模板构建 dom 树的另一种选择。
我举一个非常简单的例子
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); 
结果是
Welcome you are at mysite.This has been created by john whose age is 25.
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>
这是 html
<div>
  <ul id="list_2"></ul>
</div>
这是包含 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}));
  });