1

I need to define javascript variables containing very long html code.

Here is a short example:

var text = "Select one item:<br>";
text += "<ul class='thumbnails'><li class='span3'><a href='#' class='thumbnail'><img src='http://placehold.it/260x180' alt=''></a></li></ul>";

Since the html is going to be much much longer, I would rather work in pure html rather than append text to a javascript string.

I thought of creating a separate html file, but I guess that would require an Ajax call to fetch its content. What is the best way to deal with this?

4 Answers 4

1

As N.Zakas said on "maintainable javascript" book, you should «keep html out of javascript» to promote high mantainability of the code through loose coupling of UI layers.

Beside the ajax solution you could also place the markup as a comment in the html file and read it via javascript (as a regular DOM node) or you could use some kind of microtemplating system (e.g. handlebars) and place your markup in a script block (the idea is to put markup where is expected to be found and not into javascript logic)

Sign up to request clarification or add additional context in comments.

Comments

1

One possible solution is to use templates. There are a few JavaScript libraries that provide templating, underscore.js is one: http://underscorejs.org/#template, or more details on how to use it for templating http://www.headspring.com/blog/developer-deep-dive/an-underscore-templates-primer/

Plus underscore is great for a number of other things.

Comments

0

You could break up the text into actual HTML objects.

var thumbnailsUL = document.createElement('ul');
for (index in {your-thumbnails-list}) {
  var thumbnail = document.createElement('li');
  thumbnail.innerHTML = {whatever you need, more objects or html as text};
  thumbnailsUL.appendChild(thumbnail);
}

Ideally though, there is no reason to build this IN JavaScript - can you not emit it from the server?

Comments

0

Instead of constructing HTML in Javascript as a string, I would rather suggest you to emit those html elements in the page itself and hide while loading. Then in Javascript, you could select that container and display it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.