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

模板引擎 #2

Open
DongLee0504 opened this issue Sep 30, 2018 · 0 comments
Open

模板引擎 #2

DongLee0504 opened this issue Sep 30, 2018 · 0 comments
Labels

Comments

@DongLee0504
Copy link
Owner

DongLee0504 commented Sep 30, 2018

/*! @preserve https://github.com/wusfen */
function wutpl(tpl){
    var code = tpl
        .replace(/<%=(.*?)%>/g, '\f_html_+= $1\f') // <%= %>
        .replace(/<%(.*?)%>/g, '\f$1\f') // <% %>
        .replace(/(^|\f)([\s\S]*?)(\f|$)/g, function($, $1, $2, $3){ // \f html \f
            return '\n_html_+= "' + $2
                .replace(/\\/g, '\\\\') // \  ->  '\\'
                .replace(/\r?\n/g, '\\n') // \n  ->  '\\n'
                .replace(/"/g, '\\"') // "  ->  '\\"'
                + '"\n'
        })
    return Function('_data_', 'var _html_="";with(_data_){'+code+'}return _html_')
}

// ========== 示例与解析 ==========

// 模板
var tpl = `
<ul>
    <% for(var i=0; i<list.length; i++){ %>
    <li>
        <%= list[i].name %>
    </li>
    <% } %>
</ul>
`

// 编译模板
var render = wutpl(tpl)


// 以上模板实际上编译成了以下代码 (render函数)
function anonymous(_data_) {
    var _html_ = "";
    with (_data_) {
        _html_ += "\n<ul>\n    "
        for (var i = 0; i < list.length; i++) {
            _html_ += "\n    <li>\n        "
            _html_ += list[i].name
            _html_ += "\n    </li>\n    "
        }
        _html_ += "\n</ul>\n"
    }
    return _html_
}


// 渲染数据
var html = render({
    list:[
        {id:1, name:'wsf'},
        {id:2, name:'Tom'}
    ]
})


// 输出结果
console.log(html)
/*
<ul>
    
    <li>
        wsf
    </li>
    
    <li>
        Tom
    </li>
    
</ul>
*/


// 复以上内容到控制台运行即看到结果

github:https://github.com/wusfen/wu.tmpl.js/blob/master/9%E8%A1%8C%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0%E6%A8%A1%E6%9D%BF%E5%BC%95%E6%93%8E.js

@DongLee0504 DongLee0504 added the js label Sep 30, 2018
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