首页 > 解决方案 > 可以在模板中缩进行而不用缩进内容吗?

问题描述

下面我用换行符创建一个字符串,稍后将在电子邮件中结束。

    if (action) {
      description = `
Git pull request action:        ${action}
Git pull request for repo:      ${req.body.repository.full_name}
Git pull request for repo URL:  ${req.body.repository.html_url}

Git pull request title:         ${req.body.pull_request.title}
Git pull request description:   ${req.body.pull_request.body}
Git pull request by user:       ${req.body.pull_request.user.login}
Git pull request URL:           ${req.body.pull_request.html_url}
`
    };

但是,如果我像这样缩进这些行

    if (action) {
      description = `
        Git pull request action:        ${action}
        Git pull request for repo:      ${req.body.repository.full_name}
        Git pull request for repo URL:  ${req.body.repository.html_url}

        Git pull request title:         ${req.body.pull_request.title}
        Git pull request description:   ${req.body.pull_request.body}
        Git pull request by user:       ${req.body.pull_request.user.login}
        Git pull request URL:           ${req.body.pull_request.html_url}
     `
    };

它还缩进输出。

问题 有没有办法在不缩进输出的情况下缩进行?

标签: javascriptnode.jsecmascript-6

解决方案


目前,无法做到这一点。

然而,有一个TC39 提案来改变它(仍在draft阶段)。
所以说不定将来会有可能。

同时,您可以使用零依赖的dedent 库来实现这一点。

let dedent = require("dedent");

// ...

if (action) {
  description = dedent`
    Git pull request action:        ${action}
    Git pull request for repo:      ${req.body.repository.full_name}
    Git pull request for repo URL:  ${req.body.repository.html_url}

    Git pull request title:         ${req.body.pull_request.title}
    Git pull request description:   ${req.body.pull_request.body}
    Git pull request by user:       ${req.body.pull_request.user.login}
    Git pull request URL:           ${req.body.pull_request.html_url}
  `
};

它处理不同类型的换行符、空行、转义反引号,并保持所有其他缩进一致。


推荐阅读