js的简单模板解析

本文探讨了在编程中动态生成内容的常见需求,特别是使用JavaScript进行模板解析和构建HTML代码的过程。通过正则表达式处理模板,可以有效地将数据结合到HTML模板中,实现动态内容的展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在编程中总是会遇见很多动态生成的东西,一般我们都是通过简单的html拼接起来的

function createHtml(name, phone, addr, email, imageSrc){
        var html = '';
        html += '<div class=personInfo>'
        html += '<p>Name: ' + name + '</p>';
        html += '<p>Phone: ' + phone + '</p>';
        html += '<p>Addr: ' + addr + '</p>';
        html += '<p>Email: ' + email + '</p>';
        html += '<img src="' + imageSrc + '">';
        html += '</div>'
        return html;
    }

但是其实我们可以通过使用正则表达式来进行简单的替换,从而实现模板解析

<script type="template" id="template">
    <h2>
      <a href="{{href}}">
        {{title}}
      </a>
    </h2>
    <img src="{{imgSrc}}" alt="{{title}}">
</script>

 function replace(obj){
            var t, key, reg;
            for(key in obj){
                reg = new RegExp('{{' + key + '}}', 'ig');
                t = (t || template).replace(reg, obj[key]);
            }
            return t;
        }

来一份简单的源代码:

<!doctype html>
<html>
<head>
   <meta charset=utf-8>
   <title>Simple Templating</title>
</head>
<body>
 
    <div class="result"></div>
    
<script type="template" id="template">
    <h2>
      <a href="{{href}}">
        {{title}}
      </a>
    </h2>
    <img src="{{imgSrc}}" alt="{{title}}">
</script>


<script type="text/javascript">
    var data = [
        {
            title : 'php web appliaction',
            href : 'http://www.baidu.com',
            imgSrc : 'http://www.baidu.com'
        },
        {
            title : 'js 权威指南',
            href : 'http://www.qq.com',
            imgSrc : 'http://www.qq.com'
        }];
    var template = document.querySelector('#template').innerHTML,
        result = document.querySelector('.result');
    function _template(template, data){
        var i = 0,
            len = data.length,
            fragment = '';
        function replace(obj){
            var t, key, reg;
            for(key in obj){
                reg = new RegExp('{{' + key + '}}', 'ig');
                t = (t || template).replace(reg, obj[key]);
            }
            return t;
        }
        for(; i < len; i++){
            fragment += replace(data[i]);
        }
        return fragment;
    }
    console.log(_template(template, data));
</script>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值