Antony Courtney wrote:
function safe_html(template_string) {
// note: mapping dictionary d constructed explicitly, not based on
what's in scope where template literal appeared
var d = { x: 'strong', u: 'world'};
return template_expand(template_string, d);
}
Part of a realistic safe_html would be checking for closing > and other
mischief smuggled into the value of x. That wants x to be evaluated
first. So template strings do help a safe_html use-case.
But to make the code above more realistic, let's say the function is
called strong_world ;-). The API would be
e.innerHTML = strong_world("<%{x}>Hello, %{u}</%{x}>");
and template_expand would look like this:
function template_expand(s, d) {
return s.replace(/%{(\w+)}/g, (s, p) => d[p]);
}
This is all a bit simplistic, of course -- for one thing, only one word
naming the dictionary property to interpolate is allowed in %{...}. But
you get the idea.
You're right, there's no way to use template strings without
double-quoting and eval'ing to strip the outer quotes, and using `with`
instead of regexp lambda-replace to find the dictionary properties as
lexical identifiers -- all of which would suck:
function strong_world(s) {
var d = { x: 'strong', u: 'world'};
return template_expand(s, d);
}
function template_expand(s, d) {
with (d) return eval(s);
}
print(strong_world("`<${x}>Hello, ${u}</${x}>`"));
It's hard to separate the parsing of a template string from eager
evaluation of the expressions to interpolate. Sweet.js could do it, but
template strings are not the tool you want, and we do not want deferred
expression evaluation as part of them -- wrong default, requires eval
for the safe_html-like cases they serve.
/be
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss