Reputation: 1229
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.
Upvotes: 3
Views: 2463
Reputation: 41391
Resig has a little blog entry on creating a very lightweight template system.
Upvotes: 3
Reputation: 93
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.
Upvotes: 3
Reputation: 599
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)
.
Upvotes: 0
Reputation: 150919
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.
Upvotes: 3
Reputation: 4047
jQuery is the way to go. You can do things like this:
// create some HTML
var mySpan = $("<span/>").append("Something").addClass("highlight");
There is also a templating plugin.
Upvotes: 5
Reputation: 4555
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.
Upvotes: 4