JavaScript HERE-doc or other large-quoting mechanism? JavaScript HERE-doc or other large-quoting mechanism? javascript javascript

JavaScript HERE-doc or other large-quoting mechanism?


Some people don't like this, so be prepared for scorn and derision, but one trick is to dump your "big block of stuff" into a <script language="text"> block:

<script id='blockOfStuff' language="text">  Hi this is random stuff  <h1>Including HTML markup</h1>  And quotes too, or as one man said, "These are quotes, but  'these' are quotes too."</script>

John Resig has used that technique (or that abomination, if you prefer) for examples of his templating mechanism.

You can get at the contents with "innerText" or "innerHTML" as appropriate, or through the services of your favorite framework.

edit — note that via jQuery (contrary to what I said in a comment below) .text() does not work, though I think it should. Use .html() instead.


Not supported natively.

But since we're talking ways to make it work, here's one that (in my experience) does:

<script type="text/javascript">      var name = "Mud";    var str = "\        My name is " + name + "\        not to be confused with Bill\        or Jack or Pete or Dennis\        my name is " + name + " and it's always been\    ";    alert("Les'n one: " + str);</script>

Those back-slashes'll do the trick. Just make sure to backslash-escape any double quotes in your string since the whole block is quoted with them.

Note that this doesn't retain newlines, you have to insert them manually as "\n" prior to trailing slash on each line. On the other hand, any whitespace indentation at the beginning of each line will be included in the output.

Really this works best when you have to declare a long multiline string in a script (e.g. XML), not as good when you need to keep that string formatted exactly the way you define it.

Cheers


JavaScript can't do it but CoffeeScript, which is a thin layer on top of JavaScript, can.

Follow the link and scroll down to "Multiline Strings and Heredocs".