朋也的博客 » 首页 » 文章

js模板 underscore 简单使用教程

作者:朋也
日期:2017-02-15
类别:javascript学习笔记 


版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证

获取

使用

创建模板

<!DOCTYPE html>
<html>
<head>
  <title>demo</title>
</head>
<body>
  <div id="box"></div>
  <script type="text/template" id="tpl">
    hello, <%=name%>
  </script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/underscore.js/1.8.3/underscore-min.js"></script>
  <script type="text/javascript">
    var name = 'world';
    var render = _.template($("#tpl").html());
    $("#box").html(render({name: name}));
  </script>
</body>
</html>
result:

hello, world

遍历列表

<!DOCTYPE html>
<html>
<head>
  <title>demo</title>
</head>
<body>
  <div id="box"></div>
  <script type="text/template" id="tpl">
    <ul>
      <% _.each(list, function(v, i) { %>
        <li><%=i%>. <%=v.name%></li>
      <% }) %>
    </ul>
  </script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/underscore.js/1.8.3/underscore-min.js"></script>
  <script type="text/javascript">
    var names = [{
      name: 'tom',
      age: 21
    }, {
      name: 'jerry',
      age: 20
    }, {
      name: 'amy',
      age: 23
    }, {
      name: 'john',
      age: 15
    }]
    var render = _.template($("#tpl").html());
    $("#box").html(render({list: names}));
  </script>
</body>
</html>
result:

1. tom
2. jerry
3. amy
4. john

if判断

<!DOCTYPE html>
<html>
<head>
  <title>demo</title>
</head>
<body>
  <div id="box"></div>
  <script type="text/template" id="tpl">
    <ul>
      <% _.each(list, function(v, i) { %>
        <% if(i % 2 == 0) { %>
          <li><%=i%>. <%=v.name%></li>
        <% } %>
      <% }) %>
    </ul>
  </script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/underscore.js/1.8.3/underscore-min.js"></script>
  <script type="text/javascript">
    var names = [{
      name: 'tom',
      age: 21
    }, {
      name: 'jerry',
      age: 20
    }, {
      name: 'amy',
      age: 23
    }, {
      name: 'john',
      age: 15
    }]
    var render = _.template($("#tpl").html());
    $("#box").html(render({list: names}));
  </script>
</body>
</html>
result:

0. tom
2. amy

参考

http://underscorejs.org/