导航栏: 首页 评论列表

简易模版实现

默认分类 2015/03/16 20:08

简易模版实现,支持

format('{{0}} #{!1} #{!!2}', '<br/>', '<br/>', '&lt;br/&gt;')
=> &lt;br/&gt; <br/> <br/>

规则:默认会转码将 < 转换成 < ;不想转码可以用!直接输出;!!表示会自动接码

代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<script type="text/javascript">
<!--
var format = function (source, opts) {
    function handler(match, key) {
        var type = String(key).indexOf('!!') === 0 ? 'decode' : String(key).indexOf('!') === 0 ? 'normal' : 'encode',
            parts = key.replace(/^!!?/, '').split('.'),
            part = parts.shift(),
            cur = data,
            variable;
        while (part) {
            if (cur[part] !== undefined) {
                cur = cur[part];
            }
            else {
                cur = undefined;
                break;
            }
            part = parts.shift();
        }

        variable = cur;
        if ('[object Function]' === toString.call(variable)) {
            variable = variable(key);
        }
        if (undefined !== variable) {
            variable = String(variable);
            // encodeURIComponent not encode '
            var fr = '&|<|>| |\'|"|\\'.split('|'),
                to = '&amp;|&lt;|&gt;|&nbsp;|&apos;|&quot;|&#92;'.split('|');
            if (type === 'decode') {
                for (var i = fr.length - 1; i > -1; i--) {
                    variable = variable.replace(new RegExp('\\' + to[i], 'ig'), fr[i]);
                }
            }
            else if (type === 'encode') {
                for (var i = 0, l = fr.length; i < l; i++) {
                    variable = variable.replace(new RegExp('\\' + fr[i], 'ig'), to[i]);
                }
            }
        }

        return (undefined === variable ? '' : variable);
    }

    source = String(source);
    var data = Array.prototype.slice.call(arguments, 1),
        toString = Object.prototype.toString;
    if (data.length) {
        data = (data.length == 1 ?
            /* ie 下 Object.prototype.toString.call(null) == '[object Object]' */
            (opts !== null && (/\[object (Array|Object)\]/.test(toString.call(opts))) ? opts : data) : data);

        return source.replace(/#\{(.+?)\}/g, handler).replace(/\{\{(.+?)\}\}/g, handler);
    }
    return source;
};


function doit(){
    //Todo
    alert(format('{{0}} #{!1} #{!!2}', '<br/>', '<br/>', '&lt;br/&gt;'))
}

//-->
</script>
</head>

<body><button type="button" onclick="doit()">doit</button>

</body>

</html>


>> 留言评论