天天看點

面試題之自定義模闆引擎的簡單實作

<!DOCTYPE html>
<html >

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>String</title>
</head>

<body>
    <script>
         /**
         *自定義模闆引擎的實作
         *注意
         *    1.一個字元串中可以有多個需要渲染的模闆字元串,是以需要用到遞歸
         *步驟
         *    1.定義模闆文法{{}}
         *        正則:
         *            /\{\{(\w+)\}\}/ 比對{{}}區域
         *            exec()(https://blog.csdn.net/weixin_38659265/article/details/109307686中有exec()相關介紹)
         *            replace(regexp/substr,replacement)在字元串中用一些字元替換另一些字元,或替換一個與正規表達式比對的子串
         *    2.實作渲染函數
         *        從左至右,比對模闆字元串
         *            比對到:用資料中對應變量值替換對應字元串,使用遞歸直至沒有模闆字元串
         *            比對不到:直接傳回模闆
         */
        let template = '我是{{name}},年齡{{age}},性别{{sex}}';
        let data = {
            name: '張三',
            age: 18
        }
        console.log(render(template, data)); // 我是姓名,年齡18,性别undefined
        function render(template, data) {
            const reg = /\{\{(\w+)\}\}/; // 模闆字元串正則
            if (reg.test(template)) { // 判斷模闆⾥是否有模闆字元串
                const name = reg.exec(template)[1]; // 查找目前模闆⾥第⼀個模闆字元串的字段
                template = template.replace(reg, data[name]); // 将第⼀個模闆字元串渲染
                return render(template, data); // 遞歸的渲染并傳回渲染後的結構
            }
            return template; // 如果模闆沒有模闆字元串直接傳回
        }
    </script>
</body>

</html>