如何删除lodash模板创建的换行符?

时间:2019-01-15 14:15:40

标签: javascript webpack lodash

我正在从lodash模板(使用webpack)渲染HTML,但是lodash模板正在创建新的换行符。美化HTML将无济于事,因为这些行不是“错误”。

我用什么

<!-- Theme
============================================= -->
<%if (theme == "main") { %>
<link rel="stylesheet" href="css/theme.css" />
<% } %>

结果。 HTML <link>

上方和下方的换行符
<!-- Theme
============================================= -->

<link rel="stylesheet" href="css/theme.css" />


这就是我想要的而上下没有换行符的方式:

<!-- Theme
============================================= -->
<link rel="stylesheet" href="css/theme.css" />

可以像这样在一行代码中完成所有操作,但是长代码会变得很丑。

<!-- Theme
============================================= -->
<%if (theme == "main") { %><link rel="stylesheet" href="css/theme.css" /><% } %>

1 个答案:

答案 0 :(得分:1)

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:

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>