[英]How to remove line breaks that lodash templates create?
I am rendering HTML from lodash templates (using webpack) but lodash templates are creating new line breaks. 我从lodash模板(使用webpack)渲染HTML,但是lodash模板正在创建新的换行符。 Beautifying the HTML will not help as those lines are not "mistakes".
美化HTML将无济于事,因为这些行不是“错误”。
What I use: 我用什么:
<!-- Theme
============================================= -->
<%if (theme == "main") { %>
<link rel="stylesheet" href="css/theme.css" />
<% } %>
The result. 结果。 New line breaks above and below the HTML
<link>
HTML
<link>
上方和下方的换行符
<!-- Theme
============================================= -->
<link rel="stylesheet" href="css/theme.css" />
This is how I want it without any new line breaks above and below: 这就是我想要的而上下没有换行符的方式:
<!-- Theme
============================================= -->
<link rel="stylesheet" href="css/theme.css" />
There is a hack to do it all in one line like this but this will get ugly with long code. 可以像这样在一行中完成所有操作,但是长代码会变得很丑陋。
<!-- Theme
============================================= -->
<%if (theme == "main") { %><link rel="stylesheet" href="css/theme.css" /><% } %>
You can use _.trim()
to remove \\n
from the start and end of the result, and _.replace()
with a RegExp to convert multiple consecutive \\n
to a single one: 您可以使用
_.trim()
从结果的开头和结尾删除\\n
,并可以使用RegExp将_.replace()
转换为一个连续的\\n
:
const str = `<!-- Theme ============================================= --> <%if (theme == "main") { %> <link rel="stylesheet" href="css/theme.css" /> <% } %>`; const compiled = _.template(str); const fn = _.flow([ compiled, str => _.trim(str, '\\n'), str => _.replace(str, /(\\n)\\1+/, '$1'), ]); const result = fn({ 'theme': 'main' }); console.log(result);
.as-console-wrapper { top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.