Created
November 11, 2020 18:50
-
-
Save d3n972/a289435809865932f5670d0080e036bb to your computer and use it in GitHub Desktop.
t.js as a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class t { | |
blockregex = /\{\{(([@!]?)(.+?))\}\}(([\s\S]+?)(\{\{:\1\}\}([\s\S]+?))?)\{\{\/\1\}\}/g; | |
valregex = /\{\{([=%])(.+?)\}\}/g; | |
constructor(template) { | |
this._t = template; | |
} | |
scrub(val) { | |
return val.replace(/"/g, """); | |
} | |
get_value(vars, key) { | |
var parts = key.split('.'); | |
while (parts.length) { | |
if (!(parts[0] in vars)) { | |
return false; | |
} | |
vars = vars[parts.shift()]; | |
} | |
return vars; | |
} | |
_render(fragment, vars) { | |
return fragment | |
.replace(this.blockregex, function (_, __, meta, key, inner, if_true, has_else, if_false) { | |
var val = this.get_value(vars, key), temp = "", i; | |
if (!val) { | |
// handle if not | |
if (meta == '!') { | |
return this._render(inner, vars); | |
} | |
// check for else | |
if (has_else) { | |
return this._render(if_false, vars); | |
} | |
return ""; | |
} | |
// regular if | |
if (!meta) { | |
return this._render(if_true, vars); | |
} | |
// process array/obj iteration | |
if (meta == '@') { | |
// store any previous vars | |
// reuse existing vars | |
_ = vars._key; | |
__ = vars._val; | |
for (i in val) { | |
if (val.hasOwnProperty(i)) { | |
vars._key = i; | |
vars._val = val[i]; | |
temp += render(inner, vars); | |
} | |
} | |
vars._key = _; | |
vars._val = __; | |
return temp; | |
} | |
}) | |
.replace(this.valregex, function (_, meta, key) { | |
var val = this.get_value(vars, key); | |
if (val || val === 0) { | |
return meta == '%' ? this.scrub(val) : val; | |
} | |
return ""; | |
}); | |
} | |
render(vars) { | |
return this._render(this._t, vars); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment