Search code examples
javascripttextareatemplate-literalstemplate-strings

Javascript Template Literals and Html Textarea


To get some html to render nicely inside a textarea,

enter image description here

I have to make my code-indentation look ugly; enter image description here

What's the proper way to write my template literal, without resorting to bad indentation?


Solution

  • I'd use a separate script file instead, for which no indentation will be needed (or even appropriate) on the top level:

    // script.js
    const htmlStr =
    `<section>
        ...
    </section>`;
    document.getElementById('txtHtmlStr').defaultValue = htmlStr;
    
    <script src="./script.js"></script>
    

    I'd prefer to separate script files from HTML files anyway, they can make things easier (eg, for proper separation of concerns, for having a single entry point, to permit linting, minifying, and transpiling)