That all makes good sense, thanks. To be clear: I'm not lobbying for a change to the spec. For now I just wanted to make sure I understood the template expansion model in the current draft spec and what it can and can't do.
I need to spend more time on my project to determine if I can make it work within the expansion model of ES6's templates or whether I truly need explicit control over the dictionary and the expansion. Even if I do need such additional expressive power it's not clear this would really necessitate any change to the spec: I could use an alternative existing template library like Mustache.js or construct an even simpler one along the lines Brendan outlined or Python's string.Template() as described here: http://legacy.python.org/dev/peps/pep-0292/ Thanks for the clarification. -Antony On Tue Oct 28 2014 at 3:06:41 PM Brendan Eich <[email protected]> wrote: > 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

