Js achieve simple version of the page replacement tool method, accepts page data back to return (to avoid html code stitching)

Directly to the Code

/**
 * @AUTHOR: licunzhi
 * @DATE: 2019-5-13
 * @DESC: 自定义模板渲染工具
 * @METHOD: template 单条数据渲染方法
 * @METHOD: templateIterator 多条数据渲染方法
 * @METHOD: templatePageHtml 页面整块替换
 */
const templateUtils = {

    /**
     * 单条模板渲染工具
     *
     * @param id 原生模板id take an example
     * @param data 数据源
     * @param regex 自定义匹配正则(多数不用)
     * @returns {void | string | *}
     *
     * First: 当前js可选中范围内定义html代码脚本片段
     *  <jsCode>
     *      <script id='idTag' type='text/html'>
     *          <div>{AUTHOR}</div>
     *          <div>{LOCATION}</div>
     *          <div>{INFORMATION}</div>
     *      </script>
     *  </jsCode>
     *
     *  Second: 传入id和执行对象参数将返回包装好的html代码段(不破坏原有的代码段结构)
     *  <jsCode>
     *      const data = {}
     *      const resultHtml = templateUtils.template('idTag', data);
     *  </jsCode>
     *
     *  ALSO: templateIterator
     */
    template(id, data, regex) {
        const template = $(`script[id=${id}]`).html();
        return template.replace(regex || /\\?\{([^{}]+)\}/g, function (match, name) {
            return (data[name] === undefined) ? '' : data[name];

        });
    },

    /**
     * 多条模板渲染工具
     *
     * @param id 原生模板id
     * @param data 数据源
     * @param regex 匹配正则(多数不用)
     * @returns {void | string | *}
     * @notice 多条渲染工具以来单条工具渲染方法
     */
    templateIterator(id, data, regex) {
        let result = '';
        for (let value of data) {
            result = result + this.template(id, value, regex);
        }
        return result;
    },

    /**
     * 视图跳转替换页面指定位置方法
     *
     * @notice 该方式适合页面局部html的替换,避免引用
     * @param matchPattern 匹配选择器,推荐使用id的方式选择
     * @param url 视图解析目标地址
     * @params url 跳转需要的参数
     */
    templatePageHtml(matchPattern, url, params) {
        $.ajax({
            url: url,
            global: false,
            type: "POST",
            dataType: "html",
            data: JSON.stringify(params),
            async: true,
            success: function (html) {
                matchPattern.html(html);
            },
            error: function (msg) {
                console.error('*************templatePageHtml**************');
                console.error(' replace html info error ..', msg);
                console.error('*************templatePageHtml**************');
            }
        })
    }
};

how to use

First to introduce this js file

Just what method you use, or import documents, or add js code snippet directly from your code

html script

I assume this is the side of the code, I want this result snippet embedded in a wrapped position on the page. Note that this script type is the type of html, and above get an id, please remember this id should be unique this id. So later you will use.

<script id="group-html" type="text/html">
    <div class="items">
        <p class="group-name">
            <span>{GROUP_NAME}</span>
            <span class="group-delete" id="{GROUP_ID}" onclick="deleteGroup(event)"></span>
        </p>
        <div class="group-num">
            <p><i>{TOTAL_COUNT}</i></p>
            <p>总会员数</p>
        </div>
        <p class="group-creat">
            <span>创建人:<i>{CREATOR}</i></span>
            <span>创建时间:<i>{CREATE_TIME}</i></span>
        </p>
    </div>
</script>

You need data format

This type of data returned by your ajxa time, assuming that data. data directly perhaps you can use or not but the effect of the final package json should be like this.

data = {
	CROUP_NAME: 'sakura',
	GROUP_ID: 123123,
	TOTAL_COUNT: 123123123,
	CREATOR: 'park',
	CREATE_TIME: '2019-05-12'
}

How should you use

The first two methods there may be implemented a data or dataLis

const groupHtml = groupUtils.template('group-html', data);
$('.group-list').append(groupHtml);

Similarly, suppose your code data is an array of objects, you can use this

 const groupHtml = groupUtils.templateIterator('group-html', data);
 $('.group-list').append(groupHtml);

Failure

Sighted all know, this thing is a simple version of artTemplate, now suffer from the introduction of the project can not be used directly, so get yourself a blind.

I did not want to repeat create the wheel, the project can not achieve a string of code and html codes appear original mosaic is far too disgusting. Can not change the project is to change yourself.

Imitate these frameworks himself in one, or will understand their thinking a little benefit, but others thought the code more rigorous.
Hope that the future one day to the introduction of these technologies, waste of time blind-create the wheel every day province.

Published 88 original articles · won praise 17 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_32112175/article/details/90709850