tags:

views:

60

answers:

4

I have a big chunk of HTML which is a template for some data added using AJAX. I would like to store the chunk in a variable and then do replacements on tokens in it but I don't want to mess up the formatting of the html to get it into a javascript string. Is there a thing like the

<<END

command in perl which will read everything following into a string until it hits the end token?

A: 

Simply put: no.

Since you're already doing AJAX calls, why not also retrieve the template via AJAX too - probably the simplest way to get it into a JS variable.

Peter Bailey
+6  A: 

No, unfortunately, there is no such construct in JavaScript.

You have a few different options, each with its own merits:

  1. String concatenation

    :

    var html = '<div id="something">' +
                   '<p>Lots of HTML</p>' +
                   '<p>Lots of HTML</p>' +
                   '<p>Lots of HTML</p>' +
               '</div>';
    
  2. Escaping the newline

    :

    var html = '<div id="something">\
                   <p>Lots of HTML</p>\
                   <p>Lots of HTML</p>\
                   <p>Lots of HTML</p>\
                </div>';
    
  3. Array joining

    :

    var html = [
        '<div id="something">',
            '<p>Lots of HTML</p>',
            '<p>Lots of HTML</p>',
            '<p>Lots of HTML</p>',
        '</div>'
    ].join('');
    
  4. Storing it in an arbitrary hidden element

    :

    HTML:

    <textarea id="template" style="display:none;">
        <div id="something">
            <p>Lots of HTML</p>
            <p>Lots of HTML</p>
            <p>Lots of HTML</p>
        </div>
    </textarea>
    

    JavaScript:

    var html = document.getElementById('template').value;
    

    I prefer using <script type="text/html">s or HTML comments but <textarea>s seem to be quite popular.

  5. Using a full-on templating engine such as

    :
J-P
The textarea/javascript element trick is pretty cool, imo.
jsight
That text area trick is awesome, I might use that.
stimms
Me too, though I'm curious about textarea vs. div. I've always used div's.
seth
The textarea trick can be a bad idea: it will be visible to any visitor reading the page without applying CSS. One such visitor is Googlebot...
NickFitz
@Nick, that's why I tend to use <!-- HTML comments -->
J-P
A: 

The language itself doesn't provide anything for this. I have used EJS (Embedded Javascript Templates) to solve a similar problem in the past, though. It was easy to work with, and uses a programming model that should be familiar to most web programmers.

jsight
A: 

There's no such thing in vanilla JavaScript. And I don't believe there's an implementation of that statement in jQuery either.

But it should be easy to implement with a simple extension method on the String prototype.

Or you could just implement Jogn Resig's micro templating solution (he's the guy who created and maintains jQuery).

roosteronacid