10 June 2007
Html generation in JavaScript
I started playing a little bit more with JavaScript recently, and one thing that bothered me was generating HTML. For example, if you have a AJAX application of any reasonable size, it probably has to change a lot of stuff inside of the various divs or other elements as it runs. For that, you need to write a lot of ugly-looking, long-running string concatenations. So, I took an idea used by the Lisp folks or in the Ruby Markaby library and I created a library to write HTML in JavaScript. I’m not sure if I’m the first one to come up with this, but my Google-fu failed in this case, so maybe… Anyway, with my JsTemple you write something like this:
$table({cellpadding: 10}, $tr( $td( $div({klass: 'container', id: 'main'}, $h1('Foobar'), $h2('Foobar2'), $h3('Foobar3'), $h4('Foobar4'), $h5('Foobar5'), $div({id: 'layer', style: 'border: solid 3px #f00; padding: 10px;'}, $p({klass: 'foo'}, 'foo', $strong('bar')), $p({klass: 'shmoo'}, 'shmoo'))))));
And you get this:
<table cellpadding="30"> <tr> <td> <div class="container" id="main"> <h1>Foobarh1> <h2>Foobar2h2> <h3>Foobar3h3> <h4>Foobar4h4> <h5>Foobar5h5> <div id="layer" style="border: 3px solid #f00; padding: 10px;"> <p class="foo">foo<strong>barstrong>p> <p class="shmoo">shmoop> div> div> td> tr> table>
I generated the necessary data about tags / possible properties from HTML 4.01 W3C specification, so all the tags should work and invalid properties should be ignored. “Should”, because the generating was a little bit tricky and I’m not 100% sure if everything is the way it should be. The dollar sign is a bit annoying, too, but my goal was to avoid cluttering of the global namespace, especially a variable name like “i” may be quite popular… I don’t know how it works performance-wise or memory-wise either (certainly some optimizations are possible), but it seems to work under Firefox, Opera, Konqueror (Safari?) and MSIE 6/7 and it even doesn’t crash any of them in a short time, what I consider a big success. I don’t really know if this is useful at all (most people don’t seem to like balancing parenthesis or don’t know a decent editor which highlight pairs of matching parenthesis, judging by Lisp popularity), but you can grab it here. To start using it simply include the js file using
One more tip: keep in mind that jsTemple just returns a string, so you can for example use it with Prototype’s Template class.
Comments ():
Riddle, 11 June 2007, 12:48 am
Great post and approach, thanks.
But as a matter of fact, there are existing solutions for issue you’ve raised. I browsed through jQuery’s plugins repository and found few examples:
Easy DOM creation
LISP-style DOM creation
And another one
I haven’t had a chance to use them in projects, but I will surely do - this creation looks amazingly easy. I’m also going to download yours and give it a try - it’s nice to have simple standalone script sometimes.
medyk, 11 June 2007, 1:29 am
Ha!.. I’m working on template engine for php which use very similar syntax :)
Generally I prefer to work on DOM objects than on text.. all is so much clearer and easier to manage
stiff, 11 June 2007, 6:25 am
Riddle: I thought that someone already did that, thanks for the links :) But after looking at the sources, I’m also happy to admit that my library is better than the ones you pasted - it implements the whole HTML specification, while the other libraries either allow you to use only a subset of HTML tags or don’t do any validation of the stuff you create at all. I also like my syntax better…
medyk: Working on DOM objects is often a better approach, but when you have bigger amounts of stuff to generate it’s nice to have a “tighter” syntax for this task.
medyk, 11 June 2007, 5:27 pm
yeah stiff.. all I meant by my comment is that I prefer to work on DOM objects and to make things easier I’m working on template engine that uses syntax very similar to what you’ve proposed above
Vinyanov, 24 August 2007, 10:45 am
But your code clutters the window namespace. Some of the Riddle’s examples try to represent all markup in a single structure. I also wondered what it could look like. I thought that we could exploit the case-sensitiveness of properties, so that a name-value pair with an upper-case key would represent name of the structure and its value and lower-case properties would describe attributes. You know: {TITLE : ‘Contents’, title : ‘Attribute’}. Values may contain arrays of other values, objects, strings, whatever. It doesn’t seem that wrong, I guess:
{TABLE:{TR:{TD:[
{H1 : 'Title'},
{H2 : 'Subtitle'},
{DIV : [ {P: ['One', {STRONG: 'and a half'}]},
{P: ‘Two’}, ‘Three’, 4
],
‘id’ : ‘content’,
‘class’ : ‘content’,
’style’ : {
padding : 10,
border : ’solid 30px red’,
margin : 0.2
}
}
]
}}}
Single toHTML implemented in the Object prototype would then suffice to generate all code. By the way, if you have any properties heteronymous with JavaScript keywords, you can enclose them with string delimiters and use them safely in object literals: {’for’ : ‘example’} :)
And style attribute represented through an object would be a nice extra. Integers could represent pixels, floats - percents etc. Oh no, wait, JavaScript doesn’t see the difference, does it?
stiff, 25 August 2007, 9:41 am
Yes, I had some remorse about cluttering the global namespace, but I didn’t found a better way to implement things with a syntax I would like, and the whole idea was to make it s-expish ala Lisp, which implies using functions. This is also the reason I used the “$” prefix, to avoid any name clashes, because I don’t use it in normal code, nor my libraries do.
One thing I found really lacking in this solution is the inability to manipulate the template after it was created. Things get messy when there is some more complicated logic behind setting up various parts of the template.
Magento Themes, 3 December 2010, 8:43 pm
We found it very helpful for our company, I think it is really reducing great deal of time.
- John Devis
Magento Themes