javascript 模板_JavaScript模板文字指南

javascript 模板

模板文字介绍 (Introduction to Template Literals)

Template Literals are a new ES2015 / ES6 feature that allows you to work with strings in a novel way compared to ES5 and below.

模板文字是ES2015 / ES6的一项新功能,与ES5及以下版本相比,它可让您以新颖的方式处理字符串。

The syntax at a first glance is very simple, just use backticks instead of single or double quotes:

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

const a_string = `something`

They are unique because they provide a lot of features that normal strings built with quotes do not, in particular:

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

  • they offer a great syntax to define multiline strings

    它们提供了定义多行字符串的绝佳语法
  • they provide an easy way to interpolate variables and expressions in strings

    它们提供了一种简单的方法来对字符串中的变量和表达式进行插值
  • they allow you to create DSLs with template tags (DSL means domain specific language, and it’s for example used in React by Styled Components, to define CSS for a component)

    它们允许您使用模板标签创建DSL(DSL表示领域特定的语言,例如,在React by Styled Components中使用,以为组件定义CSS)

Let’s dive into each of these in detail.

让我们深入研究其中的每一个。

多行字符串 (Multiline strings)

Pre-ES6, to create a string spanning over two lines you had to use the \ character at the end of a line:

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

const string =
  'first part \
second part'

This allows to create a string on 2 lines, but it’s rendered on just one line:

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

first part second part

first part second part

To render the string on multiple lines as well, you explicitly need to add \n at the end of each line, like this:

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

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

or

要么

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

Template literals make multiline strings much simpler.

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

Once a template literal is opened with the backtick, you just press enter to create a new line, with no special characters, and it’s rendered as-is:

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

const string = `Hey
this

string
is awesome!`

Keep in mind that space is meaningful, so doing this:

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

const string = `First
                Second`

is going to create a string like this:

将创建这样的字符串:

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:

解决此问题的一种简单方法是,在第一行为空,并在结束反引号之后附加trim()方法,这将消除第一个字符之前的任何空格:

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.

标签模板是一个功能, 乍一看对您来说似乎没什么用,但是实际上它被很多流行的库使用,例如Styled ComponentsGraphQL客户/服务器库Apollo ,因此了解它的工作原理非常重要。

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

在“样式化组件”中,模板标签用于定义CSS字符串:

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:

在Apollo中,模板标记用于定义GraphQL查询架构:

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

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

这些示例中突出显示的styled.buttongql模板标签只是函数

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.

literals是一个数组,其中包含由表达式插值标记的模板文字内容。

expressions contains all the interpolations.

expressions包含所有插值。

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.

literals是具有两个项目的数组。 第一个是something ,直到第一个插值为止的字符串,第二个是空字符串,第一个插值的末尾(我们只有一个)和字符串的末尾之间的空间。

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

在这种情况下, expressions是具有单个项目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:

在这种情况下, literals是一个数组,其中第一项是:

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

在这种情况下, expressions是一个具有两项x6的数组。

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:

最简单的示例是通过连接literalsexpressions来复制字符串插值的expressions

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

and this is how interpolate works:

这是interpolate工作方式:

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

翻译自: https://flaviocopes.com/javascript-template-literals/

javascript 模板

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值