从模板字符串渲染空白

时间:2019-04-11 01:57:35

标签: javascript html whitespace

如果我的模板字符串带有空格,请说

(`${firstName},

Thanks for ordering ${product1}.

Your order has shipped.`);

如何将其呈现为html(包括空格)?

我尝试使用innerHTML,但结果为

Hello Somebody, Thanks for ordering something. Your order has shipped.
<html>
<head>
    <meta name="viewport" content="minimum-scale=1.0, width=device-width, maximum-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8">

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>

<div id="test"></div>
  <script type="text/babel">

    var firstName = "Somebody"
    var product = "something"


    const element = (`
    Hello ${firstName},

    Thanks for ordering ${product}.

   Your order has shipped.
`);

document.getElementById('test').innerHTML = element;    

</script>
</body>
</html>```

Expected:

Hello Somebody, 

Thanks for ordering something. 

Your order has shipped.


Actual results:

Hello Somebody, Thanks for ordering something. Your order has shipped.

3 个答案:

答案 0 :(得分:1)

默认情况下,HTML将折叠空白。您可以使用css white-space: pre保留空格,也可以使用<br>标签替换换行符,以呈现换行符,如下所示:

document.getElementById('test').innerHTML = element.replace(/\n/g, '<br>')

答案 1 :(得分:0)

您可以尝试使用pre标签而不是div标签:

<pre id="test"></pre>

答案 2 :(得分:0)

由于您使用babel,为什么不在const element = ( <div> <h3>Hello ${firstName}<h3> <p>Thanks for ordering ${product}</p> <p>Your order has shipped.</p> </div> ); 中编写HTML?

group_map

仅供参考,您需要先包装div