The variable is itself some html and I want to be able to format it so that it looks like HTML and not an unreadable super long one line string...
<script> var myHTML = " <div> content </div>" </script>
The only way I can see to get it to work would be to do this (really ugly)
<script> var myHTML = "" +"<div>" +"content" +"</div>" </script>
Is there a friendly way to do this?
Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:
var myHTML = '<div>\n content\n</div>'; console.log(myHTML);
A commonly used and friendly approach to this is to put the template string in its own
<script> element with the type attribute set to
This allows you to write HTML (as well as template markup) as you normally would, without the need for escaping or special handling of newlines.
A working demo of this approach:
//get the template string var myHTML = document.getElementById("template1").innerHTML; //check that myHTML contains the template string console.log(myHTML);
<script type="text/x-template" id="template1"> <div> content </div> </script>
- You just have to put backward slash "\" at the end of the each line (except last line) of the string and then press enter to go in newline.
In your case:
<script> var myHTML = '\ <div>\ content\ </div>\ '; </script>
- why not to put the whole template in a single file "template.html", then you can use an ajax httrequest to put the whole content inside a variable? This could make the whole thing much readable and easy to update.