Search code examples
javascriptstringtemplate-strings

How to append multi line template string in div?


I have a template string as follows:

var temp = `
for i in range(10):
    print i`

What I expect is that this template code should appear in between the div.
My div in index.html is:

<div id = "code" style="height:500px;top:0;border: 1px solid black;"></div>

My javascript code that trigger append is:

$('#code').append(temp);

My desired output is:

for i in range(10):
        print i 

My output is:

for i in range(10):print i

Please suggest me some way to get my desired in proper spacing and lines. I tried (temp.split('\n')).join('<br>') it prints the temp in separate lines but it doesn't ensure proper spacing. like this:

for i in range(10):
print i  

Solution

  • If you want to format text as-is, use the <pre> tag.

    The HTML Preformatted Text () represents preformatted text. Text within this element is typically displayed in a non-proportional font exactly as it is laid out in the file. Whitespaces inside this element are displayed as typed.