返回列表

15行代码的模板解析

默认分类 2014/07/31 19:07

代码如下:

function format(source, opts) {
    source = String(source);
    var data = Array.prototype.slice.call(arguments, 1);
    if (data.length) {
        data = (data.length == 1 ? (opts !== null && (/\[object (Array|Object)\]/.test(Object.prototype.toString.call(opts))) ? opts : data) : data);
        return source.replace(/#\{(.+?)\}/g, function (match, key) {
            var part, parts = key.split('.'),
                cur = data;
            while (cur && (part  = parts.shift())) {
                cur = cur[part] !== undefined ? cur[part] : undefined;
            }
            return (undefined === cur ? '' : cur);
        });
    }
}

使用方式: format('Hello #{user}', {user: 'Tom'});