Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript HERE-doc or other large-quoting mechanism?

Tags:

Is there a convenient way to quote a large block of HTML that has both single and double quotes in JavaScript?

Is there anything like a HERE-doc <<EOF, a multi-quote character """, or custom delimiters q{}?

Any creative or inventive solutions to this problem?

like image 220
NO WAR WITH RUSSIA Avatar asked Jun 01 '10 22:06

NO WAR WITH RUSSIA


2 Answers

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.

like image 94
Pointy Avatar answered Sep 30 '22 02:09

Pointy


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

like image 39
Madbreaks Avatar answered Sep 30 '22 00:09

Madbreaks