How to insert a large block of HTML in JavaScript?

后端 未结 7 866
悲哀的现实
悲哀的现实 2020-12-07 18:50

If I have a block of HTML with many tags, how do insert it in JavaScript?

var div = document.createElement(\'div\');
div.setAttribute(\'class\', \'post block         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 19:20

    This answer does not use backticks/template literals/template strings (``), which are not supported by Internet Explorer.

    Using HTML + JavaScript:

    You could keep the HTML block in an invisible container (like a

Idea from this answer: JavaScript HERE-doc or other large-quoting mechanism?

Using PHP:

If you want to insert a particularly long block of HTML in PHP you can use the Nowdoc syntax, like so:

isn't that awesome!";

    echo
<<Including HTML markup
    And quotes too, or as one man said, "These are quotes, but 'these' are quotes too."
    

The beauty of Nowdoc in PHP is that you can use variables too $some_var

Or even a value contained within an array - be it an array from a variable you've set yourself, or one of PHP's built-in arrays. E.g. a user's IP: {$_SERVER['REMOTE_ADDR']} EOT; ?>

Here's a PHP Fiddle demo of the above code that you can run in your browser.

One important thing to note: The << and EOT; MUST be on their own line, without any preceding whitespace.


One huge advantage of using Nowdoc syntax over the usual starting and stopping your PHP tag is its support for variables. Consider the usual way of doing it (shown in the example below), contrasted to the simplicity of Nowdoc (shown in the example above).



Now here's some HTML...

Let's pretend that this HTML block is actually a couple of hundred lines long, and we need to insert loads of variables

Hi !

I can see it's your birthday on , what are you hoping to get? And some more HTML!

提交回复
热议问题