介绍
正如imjared在他的答案中所说,你正在复杂化JavaScript模板的概念。但我想通过解释模板的语法来使其更加清晰。
模板包含最多四个不同的部分,你可以在模板内编写一个模板,就像我将要展示的那样,但不完全是你提到的方式。
高级字符串
首先,模板只是一种使用内部表达式编写字符串的高级方式。如果你输入:
typeof `this template` (1)
在您的浏览器控制台中,它将输出 "string"。
在旧时代,当您想要连接许多字符串时,您最终会写下以下代码:
"string1" + "string2" + ... + "stringN" (2)
有些参数可能是数字,这些数字通常会自动转换为字符串(在大多数情况下,它会按预期工作)。但是,如果您想计算一个表达式,您通常需要将该表达式写在括号之间:
"string1" + (a + b * c) + "string2" (3)
现代JavaScript有模板
模板使用${...}
特殊语法替换原有的写法。在${...}
中,您可以编写表达式。这意味着(3)可以使用模板语法重写如下:
`string1${a + b * c}string2` (4)
语法的优点在于看起来可以像这样在模板中插入变量:
`string1${varname}string2` (5)
这仍然是一个表达式,只是它被限制在varname
中。
因此,在模板中有四个可能的不同部分:
One String
If your template is just one string (i.e. no ${...}
) then it is just like a string.
`this is just like a string` (6)
Two Parts
If you have one expression within a template, then you have a HEAD and a TAIL in your template. (4) and (5) above are templates with a HEAD and a TAIL.
Three Parts
If you write a template with more than one expression, that adds one or more special parts in between the expressions. These are called MIDDLE templates.
`head${expr1}middle${expr2}middle${expr3}tail` (7)
模板内的模板
就像我上面提到的,你可以实际上在一个模板中写另一个模板。大多数情况下,你不需要这样做,但是这是可能的,因为出现在${
和}
之间的内容被视为表达式,而模板则被视为主要文字(或多或少,实际上有一点更复杂...)
`string1${v
+ `sub-template${ sub_sub_template_is_possible }tail`
+ w}string2` (8)
如(8)中的子模板示例所述,您可以在子模板中再嵌套另一个子子模板。我认为在大多数情况下,您不太可能需要这样做,因为根模板已经为您提供了所有必要的功能。
转义字符
与字符串一样,模板也支持使用反斜杠来转义各种字符:
\<octal>
\x<hexadecimal>
\u<hexadecimal>
Some special characters such as the character n
which represents the newline (\n
)
Finally, the other characters are escaped as is, this would include:
\` (9)
to escape the template quotes, in which case they are viewed as the quote character, not a template starting or ending point. In other words, string (10) is equal to string (11):
`\`` (10)
"`" (11)
非常简化的语法
以下是上述部分使用简化的 BNF 类似语法:
TemplateLiteral ::= Template
| TemplateHead TemplateExpression* TemplateTail
TemplateExpression ::= Expression
| TemplateExpression TemplateMiddle Expression
Template ::= '`' Character* '`'
TemplateHead ::= '`' Character* '${'
TemplateMiddle ::= '}' Character* '${'
TemplateTail ::= '}' Character* '`'
Character ::= ... -- characters valid in strings,
except '${' and '`' (12)
参考文献
JavaScript语言的描述可以在此页面找到ECMA-262文档:
https://www.ecma-international.org/publications-and-standards/standards/ecma-262/
搜索 模板文字词法组件。 您将找到我上面提到的四个部分(以及更多内容):Template
,TemplateHead
,TemplateMiddle
和TemplateTail
。
reactjs
,所以更可能是JSX而不是HTML5。你应该阅读:https://reactjs.org/docs/jsx-in-depth.html - Derek 朕會功夫