Converting strings to template strings

Domenic Denicola d at domenic.me
Mon Mar 23 18:35:38 UTC 2015


Is it too late to go back to quasi-literals?

(Joking!)

-----Original Message-----
From: es-discuss [mailto:es-discuss-bounces at mozilla.org] On Behalf Of Jason Orendorff
Sent: Monday, March 23, 2015 18:52
To: Mark S. Miller
Cc: Mark Miller; es-discuss at mozilla.org
Subject: Re: Converting strings to template strings

On Mon, Mar 23, 2015 at 1:55 AM, Mark S. Miller <erights at google.com> wrote:
>> String templates are not good for templates, these work only for 
>> statically defined code and in place meaning you cannot grab content 
>> from a DB and inject values like names or numbers as you would do 
>> with any templating system.
>
> I still don't understand this. Could you give a simple example and 
> explain what it is trying to do? Thanks.

Filling in templates with data is extremely useful in web development.
Many libraries do just this one thing and nothing else. [Mustache][1], [JSRender][2], and [nano][3] are all popular. Ruby has [ERB][4] built-in; there's [Jinja][5] for Python and a million more.

All these libraries work something like this:

    // You compile a template into an object.
    var t = TemplateLibrary.compile(templateFileName);
    // You pass some data to the template object and it builds a string.
    resultDiv.innerHTML = t.render({data: resultArray});

Each library is thus a compiler or interpreter for a template *language*. Template languages are interesting. The best ones are designed for simplicity and clarity. Some offer a weak safety
property: e.g. a template can't execute arbitrary JS code of its choice and will do no worse than call getters on the objects you pass to it. Various template languages thus have richer or poorer expression syntax, by design. All have straightforward loop syntax.
They are, in short, superficially like ES6 template strings, but otherwise about as different as can be. ES6 template strings are not a replacement for template libraries.

But from the few data points I have, approximately 100% of web developers, when they first hear "template strings are in ES6", think that means something like Mustache in the standard library. Some initially try to use the feature that way and get frustrated. I expect widespread confusion on this point.

-j

    [1]: https://mustache.github.io/mustache.5.html
    [2]: http://www.jsviews.com/
    [3]: https://github.com/trix/nano
    [4]: http://www.stuartellis.eu/articles/erb/
    [5]: http://jinja.pocoo.org/
_______________________________________________
es-discuss mailing list
es-discuss at mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


More information about the es-discuss mailing list