此答案不使用 Internet Explorer 不支持的反引号/模板文字/模板字符串 (``)。
使用 HTML + JavaScript:
您可以将 HTML 块保存在 HTML 代码中的不可见容器中(如 <script>),然后在运行时在 JS 中使用其 innerHTML
例如:
// Create a temporary <div> to load into
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
// You could optionally even do a little bit of string templating
div.innerHTML = div.innerHTML
.replace(/{VENDOR}/g, 'ACME Inc.')
.replace(/{PRODUCT}/g, 'Best TNT')
.replace(/{PRICE}/g, '$1.49');
// Write the <div> to the HTML container
document.getElementById('targetElement').appendChild(div);
.red {
color: red
}
<script id="blockOfStuff" type="text/html">
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but
'these' are quotes too."<br><br>
<b>Vendor:</b> {VENDOR}<br>
<b>Product:</b> {PRODUCT}<br>
<b>Price:</b> {PRICE}
</script>
<div id="targetElement" class="red"></div>
来自这个答案的想法:JavaScript HERE-doc or other large-quoting mechanism?
使用 PHP:
如果你想在 PHP 中插入一个特别长的 HTML 块,你可以使用 Nowdoc 语法,如下所示:
<?php
$some_var = " - <b>isn't that awesome!</b>";
echo
<<<EOT
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but 'these' are quotes too."
<br><br>
The beauty of Nowdoc in PHP is that you can use variables too $some_var
<br><br>
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;
?>
这是您可以在浏览器中运行的上述代码的a PHP Fiddle demo。
需要注意的重要一点:<<<EOT 和 EOT; 必须在自己的行中,前面没有任何空格!
为什么在 PHP 中使用 Nowdoc?
与通常的启动和停止 PHP 标记相比,使用 Nowdoc 语法的一个巨大优势是它支持变量。考虑一下正常的做法 - 如下例所示:
<?php
// Load of PHP code here
?>
Now here's some HTML...<br><br>
Let's pretend that this HTML block is actually a couple of hundred lines long, and we
need to insert loads of variables<br><br>
Hi <?php echo $first_name; ?>!<br><br>
I can see it's your birthday on <?php echo $birthday; ?>, what are you hoping to get?
<?php
// Another big block of PHP here
?>
And some more HTML!
</body>
</html>
与 Nowdoc 的简单性相比。