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:

You can have here-documents like this:

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:

The right way

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

Leave a Reply

Your email address will not be published.