1. 程式人生 > >編寫簡單js的mvc模板引擎

編寫簡單js的mvc模板引擎

<div id="con"></div>

<script type="text/html" id="template">
    <p>name:{{name}}</p>
    <p>age:{{age}}</p>
</script>
<script type="text/javascript">
    let data = {
        name: "wkh",
        age: 30
    };
    var mtpl = function (tpl, data) {
        var tp = document.getElementById(tpl).innerHTML;
        var reg = /\{\{(\w+)\}\}/g;
        while ((result = reg.exec(tp)) !== null) {
            console.log(result[0])
            console.log(result[1])
            if (result[1]) {
                tp = tp.replace(result[0], data[result[1]])
            }
        }
        return tp

    };

    document.getElementById("con").innerHTML = mtpl("template", data)
</script>