Heredoc variable with Javascript

Javascript is amazing in terms of unobvious features. Sometimes it solves your problem in way you never think of.

In this case I need a small HTML template to be included into my very simple JS project. Since template is multi-line I want to edit it as-is and dont mess with “+” on each line. Here is a simple and elegant solution:

Using the following function:

function hereDoc(f) {
   return f.toString().
   replace(/^[^\/]+\/\*!?/, '').
   replace(/\*\/[^\/]+$/, '');
}

You can have here-documents like this:

var tennysonQuote = hereDoc(function() {/*!
   This is HTML template,
   With second line,
   and no "+" on each line
*/});

The method has successfully been tested in the following browsers (not mentioned = not tested):

  • IE 4 – 10
  • Opera 9.50 – 12 (not in 9-)
  • Safari 4 – 6 (not in 3-)
  • Chrome 1 – 27
  • Firefox 17 – 21 (not in 16-)
  • Rekonq 0.7.0 – 0.8.0
  • Not supported in Konqueror 4.7.4

Be careful with your minifier, though. It tends to remove comments. For the YUI compressor, a comment starting with /*! (like the one I used) will be preserved.

Don’t want to bother with regexp? Use KISS version:

var myString = function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

The right way

This solution sounds like a hack, for serious project I would recommend using any Javascript template library available.

Did you find this post useful? Support the the author ($10)
My Google Profile+

Leave a Reply

Your email address will not be published.