Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字符串还可以这样玩 #11

Open
raclen opened this issue Sep 15, 2019 · 0 comments
Open

字符串还可以这样玩 #11

raclen opened this issue Sep 15, 2019 · 0 comments
Labels
博客搬迁 以前博客的文章迁移过来

Comments

@raclen
Copy link
Owner

raclen commented Sep 15, 2019

var tpl = ['{{name}}',
            '<p>我来自{{address}}</p>',
            '<p>这是我的个人博客</p>',
        ].join("");

        var data = {
            name: "<h1>你好</h1>",
            address: '湖北襄阳'
        }
        var html = tpl.replace(/{{name}}/, data.name).replace(/{{address}}/, data.address);
        document.body.innerHTML = html

这像什么,模板赋值啊,忽然发现一个新大陆,有意思
现在我把它改进了下

var tpl = ['{{name}}',
            '<p>我来自{{address}}</p>',
            '<p>这是我的个人博客</p>',
        ].join("");

        var data = {
            name: "<h1>你好</h1>",
            address: '湖北襄阳'
        }
        function htmlTpl(tpl,data){
            return tpl.replace(/{{(\w+)}}/g,function(){
                return data[arguments[1]];
            });

        }
        // var html = tpl.replace(/{{name}}/, data.name).replace(/{{address}}/, data.address);
        document.body.innerHTML = htmlTpl(tpl,data)

顺便说一下,正则的确是很好的工具,有了正则,思路又开阔了些
预览一下

#2016-07-28

@raclen raclen added the 博客搬迁 以前博客的文章迁移过来 label Sep 15, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
博客搬迁 以前博客的文章迁移过来
Projects
None yet
Development

No branches or pull requests

1 participant