I've got problem with this for a few days, I'm working on a client side framework and recently I've switched it to use ES Modules. The problem is that my templating engine now got a scope problem: I can't call helper functions anymore in my views.
Here is the code:
class templateEngine {
// Parse template (content) with parameters
static parse(content, params) {
let re = /{#(.+?)#}/g,
reExp = /(^\s*(if|for|else|switch|case|break|{|})).*/g,
code = 'with(obj) { var r=[];\n',
cursor = 0,
result,
match;
let add = function (line, js) {
js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
(code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
return add;
}
while (match = re.exec(content)) {
add(content.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(content.substr(cursor, content.length - cursor));
code = (code + 'return r.join(""); }').replace(/[\r\t\n]/g, ' ');
try {
test("test"); // This console log "test".
result = new Function('obj', code).call(this, params);
}
catch (err) {
console.error(err.message, "falling back to raw content.");
return content;
}
return result;
};
};
function test(s) {
console.log(s);
return s;
}
export default templateEngine;
Here is how I call the parse function (this load function is part of the View class):
// Load parsed template view into "viewroot"
load() {
let params = this.params;
let xhr = new XMLHttpRequest();
xhr.overrideMimeType("text/html");
xhr.open('GET', this.path, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == "200") {
// Parse view template
let parsedview = templateEngine.parse(this.responseText, params);
// Load parsed html into viewroot element
document.querySelector("viewroot").innerHTML = parsedview;
// Change page title with view title
let title = document.querySelector("viewhead").querySelector("title");
document.title = title.text;
}
};
xhr.send(null);
}
And here is the html template:
<viewhead>
<title>Welcome!</title>
</viewhead>
<viewbody>
<div class="container">
<h1 class="title">Page title</h1>
<p class="description">welcome to this page</p>
<p>{# test("test") #}</p>
</div>
</viewbody>
The "test" function is no longer accessible from the "result" Function object.
Vanilla javascript and non-module functions are accessible and working but module ones are not.
Hope you can help me with this one.