在html文件中使用art-template

代码演示

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test</title>
</head>
<body>
<form id="user_form">

</form>

<!-- 此处要有 type="text/template" id="xxx" -->
<script type="text/template" id="tpl">
  姓名:<input type="text" value="{
     
     {user.username}}">
  <br>
  年龄:<input type="text" value="{
     
     {user.age}}">
  <br>
  职业:
  <select name="">
    {
     
     {
     
     each jobs}}
    {
     
     {
     
     if $value.id === user.job}}
    <option value="{
     
     {$value.id}}" selected>{
     
     {
     
     $value.name}}</option>
    {
     
     {
     
     else}}
    <option value="{
     
     {$value.id}}">{
     
     {
     
     $value.name}}</option>
    {
     
     {
     
     /if}}
    {
     
     {
     
     /each}}
  </select>
</script>

<!--引入template-web.js文件-->
<script src="./template-web.js"></script>
<!--引入jquery.js文件-->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$(function () {
     
     
	//获取数据
    $.get('http://localhost:3001/users/3', function (userData) {
     
     
      $.get('http://localhost:3001/jobs', function (jobsData) {
     
     
      
		//template()的返回值是一个拼接好的字符串
        let result = template('tpl', {
     
     
          user: userData,
          jobs: jobsData
        });
        //渲染到页面上
        document.getElementById("user_form").innerHTML = result;
      })
    })
  });
</script>
</body>
</html>
  1. 代码中的 template-web.js 文件我们可以通过 npm install art-template 安装上art-template 后拿到这个文件,或者去官网下载 https://github.com/aui/art-template
  2. 代码中我开启了一个 json-server 本地服务,有关json-server的介绍可以查看这篇文章 json-server的基本使用
  3. 代码中使用到的数据如下
{
    
    
  "users": [
    {
    
    
      "id": 1,
      "username": "admin1",
      "age": 18,
      "job": 1
    },
    {
    
    
      "id": 2,
      "username": "admin2",
      "age": 28,
      "job": 2
    },
    {
    
    
      "id": 3,
      "username": "admin3",
      "age": 38,
      "job": 3
    }
  ],
  "jobs": [
    {
    
    
      "id": 1,
      "name": "学生"
    },
    {
    
    
      "id": 2,
      "name": "老师"
    },
    {
    
    
      "id": 3,
      "name": "司机"
    },
    {
    
    
      "id": 4,
      "name": "黑客"
    },
    {
    
    
      "id": 5,
      "name": "画家"
    }
  ]
}

猜你喜欢

转载自blog.csdn.net/weixin_43974265/article/details/112403302