Simone Simone - 1 year ago 68
HTML Question

Breaking a string into multiple lines inside a javascript code

I am trying to format (beautify, tidy, clear up.. you name it) a snippet of HTML inside my javascript code or, in other words, spread it out on multiple lines rather than having it written on one line so it can be read easily.

Basically, it's a piece of html code that I am trying to append to the page by calling the jQuery's


And here's what I am trying to do:

<span>' + count + '</span> -
<a href="' + vList[i].player + '">
<span class="title">' + videoTitle + '</span>

Appearantly, it won't work that way. I am getting
Uncaught SyntaxError: Unexpected token >

When It is written as follows, everything works fine.

$('.videos').append('<li><span>' + count + '</span> - <a href="' + vList[i].player + '"><span class="title">' + videoTitle + '</span></a></li>');

It's kind of weird that when I tried to do the exact thing here,

var albumURL = API + '/video.get?=owner_id=' + userID +
'&album_id=' + aList[i].album_id +
'&access_token=' + accessToken;

I had no problem at all.

I know this issue is not that big of a deal but I am trying to get around with it just for the sake of simplicity.

Any suggestions?

Answer Source

If you have a multiline string, you need to use the multiline string syntax.

However, it's better to store your HTML in templates and not code :) That makes them more readable, more reusable and more maintainable.

What about something like - in your HTML:

<script type="text/template" id="videoTemplate">
      <a href="{{videoURL}}">
        <span class="title">{{videoTitle}}</span>

Then in JavaScript

var template = $("#videoTemplate").html();

That way, you get a clearer separation of the template you're using and your code. You can change the HTML independently and reuse it in other parts of code more easily.

The code does not have to even be aware of template changes and a designer can change the design without knowing JavaScript.

Of course, if you find yourself doing this often you can use a templating engine and not having a .replace chain.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download