天天看点

thymeleaf前端数据绑定

thymeleaf是一种模板,如果想在html对表格进行绑定,可以这么做:

<html xmlns:th="http://www.thymeleaf.org">
<script th:src="@{../pages/js/art-template/art-template.js}"></script>

</html>      

解释一下,xmlns指定了我们使用thymeleaf模板,然后就可以进行数据绑定,另外,加入的template.js主要是进行列表的绑定,这个.js文件可以到网上下载之后然后放到项目中去。

<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<script th:src="@{../pages/js/art-template/art-template.js}"></script>
<div id="table-box"></div>
<script id="demo_table" type="text/html">
<table>
  <thead>
    <tr>
    <th>name</th>
    <th>gender</th>
    <th>age</th>
    <th>occupation</th>
    <th>zip_code</th>
    </tr>
  </thead>
  <script>
  <tbody>
  {{if $data}}
  {{each $data}}
    <tr>
      <td>{{value.name}}</td>
      <td>{{value.gender}}</td>
      <td>{{value.age}}</td>
      <td>{{value.occupation}}</td>
      <td>{{value.zip_code}}</td>
    </tr>
  {{/each}}
  {{/if}}
  </tbody>
<table>
</script>
<script th:src="@{../pages/js/demo.js}"></script>
</body>
</html>      
function demo(){
  data = {
      "info":[
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000},
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000},
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000},
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000},
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000},
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000},
        {"name":"1","gender":"F","age":18,"occupation":"java IT Projecter","zip_code":100000}
      ]
  }
  var html = template('demo_table', data.info);
  document.getElementById('table_box').innerHTML = html;
}