template-web.js: 高性能模板引擎art-template渲染html

art-template模板渲染HTML

該方法的核心思想就是將json數據傳入按照art-template模板編寫模板中去。

  • filename: 對於模板的script標籤的id;
  • data: js獲取的數據(一般是後端返回的序列化json字符串)
// 基於模板名渲染模板
template(filename, data);

這樣就可以把這部分的模板添加到template模板中去,更多的詳情可以參考art-template網站

具體示例參考如下:

前端部分

下載template-web.js文件,在HTML文件中導入,並編寫包含渲染的script標籤。

<!-- file: course_teacher.html -->
{% extends 'cms/base.html' %}
{% load rest_framework %}
{% block title %}
    課程老師
{% endblock %}

{% block head %}
{#  引入arttemplat  #}
    <script src="{% static 'js/template-web.js' %}"></script>
    <script src="{% static 'js/index.js' %}"></script>
{% endblock %}

{% block main %}
<div class="box-body">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>id</th>
                <th>姓名</th>
                <th>職稱</th>
                <th>簡介</th>
                <th>操作</th>
                <th>頭像</th>
            </tr>
        </thead>
        <tbody id="course-teacher-list">
        
        <script id="course-teacher-list-tmpl" type="text/html">
		{# 該標籤是django標籤(阻止模板引擎呈現此block標記的內容),用於指示包裹的文件不處理,只作爲字符串 #}
        {% verbatim %}
        {{ each course_teachers as teacher }}
            <tr  data-pk="{{ teacher.id }}" data-name="{{ teacher.username }}" data-jobtitle="{{ teacher.jobtitle }}" data-profile="{{ teacher.profile }}" data-avatar="{{ teacher.avatar }}">
                <td>{{ teacher.id }}</td>
                <td>{{ teacher.username }}</td>
                <td>{{ teacher.jobtitle }}</td>
                <td>{{ teacher.profile }}</td>
                <td><img src="{{ teacher.avatar}}" alt="" style="height: 40px"></td>
                <td>
                    <button id="edit-btn" type="button" class="btn btn-warning btn-xs edit-btn">編輯</button>
                    <button class="btn btn-danger btn-xs delete-btn">刪除</button>
                </td>
            </tr>
        {{ /each }}
        {% endverbatim %}
        </script>
        
        </tbody>
    </table>
</div>
{% endblock %}
// file: course_teacher.js
// 老師信息js渲染方法
function getTeacherInfo () {
    $.get("/cms/course_teacher_list/?format=json", function (resp) {
        if(resp){
            $("#course-teacher-list").html(template("course-teacher-list-tmpl", {course_teachers:resp}));
        }else {
            console.log("django-rest-framework沒有返回數據!");
        }
    });
}
後端部分

通過'"/cms/course_teacher_list/?format=json"'請求返回序列化的json數據,返回數據類型示例:

 [
    {
        "id": 7,
        "username": "馬雲",
        "jobtitle": "董事會成員",
        "profile": "阿里巴巴創始人",
        "avatar": "https://dss2.bdstatic.com/6Ot1bjeh1BF3odCf/it/u=1775658611,2908181310&fm=74&app=80&f=JPEG&size=f121,140?sec=1880279984&t=110d52194c540f019513ffa7b0bc367e"
    },

      ......

    {
    "id": "",
    "username": "",
    "jobtitle": "",
    "profile": "",
    "avatar": ""
}

]
最終效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章