mustache+mock

mustache.js 模板引擎

mock.js 数据渲染

 

- 页面结构 | index.html

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="./js/jquery.min.js"></script>
    </head>

    <body>
        <!-- 页面结构 -->
        <div class="tabview" id="tab"></div>

        <!-- 模板 -->
        <script type="text/x-template" id="tab-tmpl">
            <div class="tab-hd">
                {{#.}}
                <a class="tab-name active" href="javascript:;"> {{name}} </a>
                {{/.}}
            </div>
            <div class="tab-bd">
                {{#.}}
                <ul class="tab-items">
                    {{#list}}
                    <li class="tab-item">
                        <span class="item-title">{{title}}</span>
                        <span class="item-author">{{author}}</span>
                    </li>
                    {{/list}}
                </ul>
                {{/.}}
            </div>
        </script>

        <!-- 工具js -->
        <script src="./mock/mock-min.js"></script>
        <script src="./mock/mock-index.js"></script>
        <script src="./js/mustache.min.js"></script>
        <!-- 页面js -->
        <script src="./js/index.js"></script>
    </body>
</html>

- mock数据 | mock-index.js

// tab栏
Mock.mock('test/getTabData', function () {
    return Mock.mock({
        data: [{
            name: '唐诗',
            'list|5': [{
                title: '@cword(5, 30)',
                author: '@cname()'
            }]
        }, {
            name: '宋词',
            'list|5': [{
                title: '@cword(5, 30)',
                author: '@cname()'
            }]
        }],
        status: {
            code: 200,
            message: 'success'
        }
    });
});

- js 部分 | index.js

$(function () {
    var $tab = $('#tab'),
        tabTmpl = $('#tab-tmpl').html();

    // Mustache.parse(tabTmpl);

    // 渲染
    function renderTabData(data) {
        // 渲染tab列表
        $tab.html(Mustache.render(tabTmpl, data));
    }

    // 请求-数据
    $.ajax({
        url: 'test/getTabData',
        type: 'POST',
        dataType: 'json',
        data: {},
        success: function (res) {
            // console.log(res.data);
            renderTabData(res.data);
        }
    });
});

 

『推荐阅读』

1. js模板引擎mustache介绍及实例

 

posted @ 2021-12-13 15:26  自在逍遥处  阅读(26)  评论(0编辑  收藏  举报