Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Techniques to avoid building HTML strings in JavaScript?

It is very often I come across a situation in which I want to modify, or even insert whole blocks of HTML into a page using JavaScript. Usually it also involves changing several parts of the HTML dynamically depending on certain parameters.

However, it can make for messy/unreadable code, and it just doesn't seem right to have these little snippets of HTML in my JavaScript code, dammit.

So, what are some of your techniques to avoid mixing HTML and JavaScript?

like image 202
amcashcow Avatar asked Jan 21 '11 10:01

amcashcow


1 Answers

The Dojo toolkit has a quite useful system to deal with HTML fragments/templates. Let's say the HTML snippet mycode/mysnippet.tpl.html is something like the following

<div>
  <span dojoAttachPoint="foo"></span>
</div>

Notice the dojoAttachPoint attribute. You can then make a widget mycode/mysnippet.js using the HTML snippet as its template:

dojo.declare("mycode.mysnippet", [dijit._Widget, dijit._Templated], {
  templateString: dojo.cache("mycode", "mysnippet.tpl.html"),

  construct: function(bar){
    this.bar = bar;
  },
  buildRendering: function() {
    this.inherited(arguments);
    this.foo.innerHTML = this.bar;
  }
});

The HTML elements given attach point attributes will become class members in the widget code. You can then use the templated widget like so:

new mycode.mysnippet("A cup of tea would restore my normality.").placeAt(someOtherDomElement);

A nice feature is that if you use dojo.cache and Dojo's build system, it will insert the HTML template text into the javascript code, so that the client doesn't have to make a separate request.

This may of course be way too bloated for your use case, but I find it quite useful - and since you asked for techniques, there's mine. Sitepoint has a nice article on it too.

like image 96
Frode Avatar answered Sep 20 '22 21:09

Frode