10

Possible Duplicate:
Multiline strings in Javascript

In Ruby you can do something like this:

temp = <<-SQLCODE
  select * from users
SQLCODE

This way you have very long string literals in your code without having to escape lots of characters. Is there something similar in JavaScript?

Currently I have JavaScript code like this, and it's driving me nuts...

  new Element.update(lightbox_id, " \
    <div id='overlay' class='overlay' > \
    </div> \
    <div id='lightbox' class='lightbox'> \
      <div class='lightbox_title'> \
        <div class='corner_image' onclick=\"close_lightbox();return false;\"><a href='#'>" + corner_image + "</a></div> \
        <div class='lightboxname' id='lightboxname'>" + title + "</div> \
        <div class='close_image'> \
          <a href='#' onclick=\"close_lightbox();return false;\">Close</a> or Escape key\
        </div> \
      </div> \
      <div id='" + lightbox_content_id + "' class='lightbox_content'>    \
      </div> \
      <script>  \
        watch_for_escape(); \
      </script> \
    </div> \
");
kahlan88
  • 101
  • 1
  • 8
Janak
  • 5,025
  • 8
  • 34
  • 43
  • Short answer: no, you can't have literal newlines in JS strings without the continuation character. A few other suggestions here: http://stackoverflow.com/questions/805107/multiline-strings-in-javascript – Shog9 May 22 '09 at 05:17

3 Answers3

6

The syntax you are referring to is often known as here-document (or HEREDOC) and no, it is not available in Javascript.

Adding a backslash as you have been doing is the appropriate way to span strings over multiple lines in JavaScript.

thomasrutter
  • 114,488
  • 30
  • 148
  • 167
3

Having html inline like that is bad practice, but if you really want to handle it cleaner, try this:

Place a hidden div on your page with the html you want, and replace the custom params with something like {title}. When calling update, pass yourdiv.innerHTML.replace(...

Luke Schafer
  • 9,209
  • 2
  • 28
  • 29
  • The problem with this approach is that it makes it difficult to encapsulate functionality within a single Javascript file - for example, writing a plugin that needs to insert specific content into the DOM. – alexw Nov 05 '15 at 01:54
0

If you're using Rails, then it becomes a lot cleaner with rjs to update a div with some multiline HTML:

page.replace__html 'lightbox_id', :partial => 'overlay'

then overlay.html.erb would contain the raw html above without escaping.

The added benefit is that the fragment 'overlay' could also be used in the initial page load as well, which in a lot of cases is what you want.

Julian H
  • 1,809
  • 17
  • 18