5
Instead of doing:
var html = '<a href="' + data.href + '" title="' + data.title + '">' + data.desc + '</a>';
I’m making:
var html = '<a href="{href}" title="{title}">{desc}</a>';
html = html
.replace( '{href}', data.href )
.replace( '{title}', data.title )
.replace( '{desc}', data.desc );
Or replace( /{nome}/g, data.nome )
if there are several occurrences.
Is there any "official" way or each has to solve on their own by creating a custom function?
I found a couple of old plugins for jQuery, 2007 and 2008. Did anything change from there to here? The frameworks Javascript, like jQuery or Mootools, already incorporate this? If so, what is the JS behind it?
There is the conveniently baptized sprintf.js, although it is not native
– William Barbosa
I usually use the Mootools element builder for cases similar to what you put http://jsfiddle.net/j1tknqj7/, but I think a JS version of
sprintf
does not exist. I will put a suggestion when my child is in bed and if there is not yet a good suggestion.– Sergio
There are template systems that solve this. With handlebars or mustache, you would have
'<a href="{{href}}" title="{{title}}">{{desc}}</a>'
compiled as template, and then only passes the objectdata
for the template he solves.– bfavaretto
@bfavaretto, I forgot to comment that my inspiration came from moustache. My intention is something more basic for handling html strings within js code.
– brasofilo