tags:

views:

183

answers:

6

I'd like to know your thoughts about HTML code generation in my JS code.

I just think that the html.push("<tag>" + something + "</tag>") style pretty annoying. I've already tried something with templates inside my HTML file (and put some placeholders therein), and then used its content to a replace the placeholders to my real values.

But maybe you guys have other ideas, possibly one using jQuery.

+4  A: 

You can use createelement, appendchild, and innerHTML to do this.

Here's an article from A List Apart that uses these functions in the process of generating a dropdown menu.

Evan Meagher
+3  A: 

jQuery is the way to go. You can do things like this:

// create some HTML
var mySpan = $("<span/>").append("Something").addClass("highlight");
  • it is cross-browser compatible,
  • it is an easy to use syntax

There is also a templating plugin.

Mat Ryer
+3  A: 

I'm a big fan of how PrototypeJS handles templates.

First you create an instance of the Template class and pass it a string containing the template HTML.

var tpl = new Template('Here is a link to <a href="#{link}">#{sitename}</a>');

Then you pass it data containing the values to replace within the template.

$('someDiv').innerHTML = tpl.evaluate( {link: 'http://www.stackoverflow.com', sitename: 'StackOverflow'} );

In the above example, I have a div with id="someDiv" and I'm replacing the contents of the div with the result of the template evaluation.

Mark Biek
A: 

There are a bunch of JQuery function that support this. In particular, you should look at append(content), appendTo(content) prepend(content) prependTo(content), replaceWith(content), after(content), before(content), insertAfter(content), and insertBefore(content).

Sean
+3  A: 

jQuery has javascript template plugins like jBind and jTemplate. I haven't used them myself but I do recommend jQuery whenever possible.

A note on html generation, it is not searchable by search engines in most cases.

Scott
+3  A: 

Resig has a little blog entry on creating a very lightweight template system.

altCognito