4

Possible Duplicate:
Is there a best practice for generating html with javascript

I want to generate large parts of a website with JavaScript.

The straightforward way is to form one large string containing all the HTML:

'<div>'
   + '<span>some text</span>'
   + '<form>'
      + '<input type="text" />'
...

But this gets quite annoying when one has to write a few hundred lines in this style. And the pain when such code has to be changed later on...

Can you think of an easier way?

Community
  • 1
  • 1
Christoph Wurm
  • 1,072
  • 1
  • 14
  • 31
  • Using jQuery you can do it in a more "organized" way by providing data in objects etc. rather than one big string. It will be slower though I guess. – pimvdb Jul 22 '11 at 11:49

4 Answers4

6

Create snippets as templates, put them into an invisible <div>:

<div style="display: none">
   <div id="template1">
      <h2 class="header_identifyingClass">Hello from template</h2>
   </div>
   <div id="template2">
      <span class="content">Blah blah</span>
   </div>
</div>

Then find it,

document.getElementById("template1"); 

fill it's internal values, e.g. find inside elements by XPath or jQuery and fill them e.g. using element.innerHTML = "Hello from new value", and move or copy it to the visible part of DOM.

Create multiple templates and copy it multiple times to generate many. Don't forget to change the ID for copies to keep it working.

PS: I think I used this approach in the code of JUnitDiff project. But it's buried in XSLT which serves another purpose.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
  • Beat me to it. This is my preferred approach. If done correctly this is much more maintainable than constructing/concatenating HTML strings in JavaScript. – aroth Jul 22 '11 at 11:50
  • Good answer, but think about what would happen if someone has CSS turned off... they'll see your templates. Consider instead a JavaScript based templating engine. – clinton3141 Jul 22 '11 at 17:16
1

By far the best way to do this is to use some kind of JavaScript templating system. The reason why this is better than hiding HTML with CSS is that if (for example) someone has CSS disabled, they'll be able to see your templates, which is obviously not ideal.

With a templating system, you can put the templates in a <script> tag, meaning that they're totally hidden from everything except JavaScript.

My favourite is the jQuery templating system, mostly because jQuery is so ubiquitous these days. You can get it from here: http://api.jquery.com/category/plugins/templates/

An example (taken from the jQuery docs):

<ul id="movieList"></ul>

<!-- the template is in this script tag -->    
<script id="movieTemplate" type="text/x-jquery-tmpl">
    <li><b>${Name}</b> (${ReleaseYear})</li>
</script>

<!-- this script will fill out the template with the values you assign -->    
<script type="text/javascript">
    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
        { Name: "The Inheritance", ReleaseYear: "1976" }
    ];

    // Render the template with the movies data and insert
    // the rendered HTML under the "movieList" element
    $( "#movieTemplate" ).tmpl( movies )
        .appendTo( "#movieList" );
</script>

It's a simple example, but you could put all of the HTML you'd like to generate in the <script>, making it much more flexible (use the same HTML snippet for various jobs, just fill out the gaps), or even use many templates to build up a larger HTML snippet.

clinton3141
  • 4,751
  • 3
  • 33
  • 46
0

Use a dialect of JavaScript such as CoffeeScript. It has heredocs:

'''
  <div>
    <span>some text</span>
    <form>
      <input type="text" />
'''

If you need to throw in an occasional expression, you can use interpolations:

"""
  <title>#{title}</title>
"""
ngn
  • 7,763
  • 6
  • 26
  • 35
0

If it's static content that you're just adding to the page on a javascript event, you could consider simply having it in your main HTML page all along, but style with display:none;.

Then it's just a case of changing it's style to make it appear on the page. Much easier.

Even if it's dynamic, you could use this technique: have the shell HTML content there hidden in your page, and populate the dynamic bits before making it visible.

hope that helps.

Spudley
  • 166,037
  • 39
  • 233
  • 307