JavaScript模板文字指南

在ES2015(也称为ES6)中引入的Template Literals提供了一种声明字符串的新方法,同时还提供了一些已经广受欢迎的有趣的新构造。

模板文字简介

模板文字是ES2015 / ES6的新功能,与ES5及以下版本相比,您可以通过新颖的方式使用字符串。

乍一看语法非常简单,只需使用反引号而不是单引号或双引号即可:

const a_string = `something`

它们之所以独特,是因为它们提供了很多用引号构建的普通字符串所没有的功能,尤其是:

  • 它们提供了定义多行字符串的绝佳语法
  • 它们提供了一种简单的方法来对字符串中的变量和表达式进行插值
  • 它们允许您使用模板标签创建DSL(DSL表示域特定的语言,例如,在React by Styled Components中使用,以为组件定义CSS)

让我们详细研究其中的每一个。

多行字符串

在ES6之前的版本中,要创建一个跨越两行的字符串,您必须使用\行尾的字符:

const string =
  'first part \
second part'

这允许在两行上创建一个字符串,但是仅在一行上呈现:

first part second part

要同时在多行上呈现字符串,您明确需要添加\n在每一行的末尾,如下所示:

const string =
  'first line\n \
second line'

或者

const string = 'first line\n' + 'second line'

模板文字使多行字符串更简单。

使用反引号打开模板文字后,您只需按Enter即可创建新行,不包含任何特殊字符,并且按原样呈现:

const string = `Hey
this

string
is awesome!`

请记住,空间是有意义的,因此请执行以下操作:

const string = `First
                Second`

将要创建一个像这样的字符串:

First
                Second

an easy way to fix this problem is by having an empty first line, and appending the trim() method right after the closing backtick, which will eliminate any space before the first character:

const string = `
First
Second`.trim()

Interpolation

Template literals provide an easy way to interpolate variables and expressions into strings.

You do so by using the ${...} syntax:

const myVariable = 'test'
const string = `something ${myVariable}` //something test

inside the ${} you can add anything, even expressions:

const string = `something ${1 + 2 + 3}`
const string2 = `something ${doSomething() ? 'x' : 'y'}`

Template tags

Tagged templates is one feature that might sound less useful at first for you, but it’s actually used by lots of popular libraries around, like Styled Components or Apollo, the GraphQL client/server lib, so it’s essential to understand how it works.

In Styled Components template tags are used to define CSS strings:

const Button = styled.button`
  font-size: 1.5em;
  background-color: black;
  color: white;
`

In Apollo template tags are used to define a GraphQL query schema:

const query = gql`
  query {
    ...
  }
`

The styled.button and gql template tags highlighted in those examples are just functions:

function gql(literals, ...expressions) {}

this function returns a string, which can be the result of any kind of computation.

literals is an array containing the template literal content tokenized by the expressions interpolations.

expressions contains all the interpolations.

If we take an example above:

const string = `something ${1 + 2 + 3}`

literals is an array with two items. The first is something, the string until the first interpolation, and the second is an empty string, the space between the end of the first interpolation (we only have one) and the end of the string.

expressions in this case is an array with a single item, 6.

A more complex example is:

const string = `something
another ${'x'}
new line ${1 + 2 + 3}
test`

in this case literals is an array where the first item is:

;`something
another `

the second is:

;`
new line `

and the third is:

;`
test`

expressions in this case is an array with two items, x and 6.

The function that is passed those values can do anything with them, and this is the power of this kind feature.

The most simple example is replicating what the string interpolation does, by joining literals and expressions:

const interpolated = interpolate`I paid ${10}€`

and this is how interpolate works:

function interpolate(literals, ...expressions) {
  let string = ``
  for (const [i, val] of expressions.entries()) {
    string += literals[i] + val
  }
  string += literals[literals.length - 1]
  return string
}

More js tutorials: