Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template strings with JavaScript

I'm writing an application with some client-side JS that I use to update the DOM reasonably often.

The thing is that doing something like:

$('#id').html('<div class="' + class + '">' + content + '</div>');

multiple times and leaving HTML lying randomly round your JavaScript isn't very pretty and difficult to maintain.

Is there a JavaScript equivalent (or alternate solution) to the way Lithium handles this in it's view helpers.

See:

  • http://li3.me/docs/lithium/template/Helper::_render()
  • http://li3.me/docs/lithium/util/String::insert()

For examples.

Basically in the PHP version you would make an associate array of common strings and a simple method to replace to replace certain marked parts of those strings with variables of the same name.

Another silly example (psuedo-code:)

var strings = {
    'div': '<div {:attr}>{:content}</div>'
};
console.log(render('div', {id: 'newElem'}, 'Hello, World!'));
// Output: <div id="newElem">Hello, World!</div>

If you have any better suggestions on how you handle storing HTML in your JavaScript and keep it from going all over the place then I'd very much like to hear it.

like image 524
rich97 Avatar asked Aug 08 '11 15:08

rich97


3 Answers

Yes, use jQuery templates or Underscore templates (my favorite) or any other JS templating engine out there.

Also, check this question for a discussion on performance of templating engines: Improve jQuery template performance

like image 105
Mrchief Avatar answered Sep 19 '22 07:09

Mrchief


If you don't want to use a templating system, and have many html snippets that must be created many times, then you can use another technique :

  1. Create a div in your main html file, give it a specific css class or id
  2. Using css, make this div invisible
  3. Inside is div, create the "template" divs, each one will contain a "snippet", each one with proper class or id
  4. Using js (jquery, whatever) when you need it, clone the "template" div, append it where you need it, and then customize it.

Using jquery this is very easy, and your template "divs" are asy accessible to any html designer.

I'm on a mobile device now, and posting code snippets is a bit difficult, but let me know if want some examples.

like image 31
Simone Gianni Avatar answered Sep 23 '22 07:09

Simone Gianni


jQuery encourages you to dynamically construct your DOM nodes instead of doing string concatenation:

$("#id").html(
    $("<div />").addClass(class).text(content))

In general, you can use the jQuery attribute methods to construct such nodes, and many of these methods take mappings as you say you like. For example:

$("#id").append(
    $("<div />")
        .attr({id: "newElem"})
        .css({width: "100%", color: "red"}))
like image 28
Eli Courtwright Avatar answered Sep 19 '22 07:09

Eli Courtwright