Breaking a string into multiple lines inside a javascript code

Simone picture Simone · Oct 11, 2013 · Viewed 24.2k times · Source

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 .append(); method.

And here's what I am trying to do:

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

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

Benjamin Gruenbaum picture Benjamin Gruenbaum · Oct 11, 2013

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">
    <li>
      <span>{{count}}</span>
      <a href="{{videoURL}}">
        <span class="title">{{videoTitle}}</span>
      </a>
    </li>
</script>

Then in JavaScript

var template = $("#videoTemplate").html();
$(".videos").append(template.replace("{{count}}",count).
                             replace("{{videoURL}}",vList[i].player).
                             replace("{{videoTitle}}",videoTitle));

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.

ES2015 also introduces template strings which are also kind of nice and serve the same purpose in principle:

 const videoTemplate = `<li>
      <span>${count}</span>
      <a href="${vList[i].player}">
        <span class="title">${videoTitle}</span>
      </a>
    </li>`;