javascript - 可以在模板中缩进行而不缩进内容吗?

标签 javascript node.js ecmascript-6

下面我将创建一个带有换行符的字符串,稍后将出现在电子邮件中。

    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}
     `
    };

它还会缩进输出。

问题 有没有办法缩进行而不缩进输出?

最佳答案

目前还无法做到这一点。

但是有一个TC39 proposal to change that (仍处于草案阶段)。
所以也许将来是可能的。

同时,您可以使用零依赖 dedent library这正是这样做的。

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}
  `
};

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

关于javascript - 可以在模板中缩进行而不缩进内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66548165/

相关文章:

javascript - 如何将值设置为javascript对象元素中的函数?

angularjs - Karma 覆盖率报告显示所有包含 100% 和 require 语句的文件

javascript - 从数组值创建 JavaScript 对象

javascript - 如何根据随机尺寸绘制正方形并显示大小

javascript - 如何将脚本添加为代码?

node.js - 使用代理时 Node Express : res. 重定向中断

Node.js - res.redirect 不起作用

node.js - Typescript登录功能打字问题

javascript - 替换字符串的最后一部分,javascript

javascript - 我们是否仍然需要 ES6 中的原型(prototype)来让所有类实例共享一个方法副本?