[英]In Pug Interpolation, what's the real difference between using buffered code and using #{..}?
As stated in the docs for interpolation:如插值文档中所述:
- var title = "On Dogs: Man's Best Friend"; - var author = "enlore"; - var theGreat = "<span>escape;</span>": h1= title p Written with love by #{author} p This will be safe: #{theGreat}
title
follows the basic pattern for evaluating a template local, but the code in between#{
and}
is evaluated, escaped, and the result buffered into the output of the template being rendered.title
遵循本地评估模板的基本模式,但#{
和}
之间的代码被评估、转义,并将结果缓冲到正在呈现的模板的 output 中。This can be any valid Javascript expression, so you can do whatever feels good.这可以是任何有效的 Javascript 表达式,因此您可以做任何感觉良好的事情。
However, the buffered code in h1= title
is still "evaluated, escaped, buffered...", and "supports the full range of JavaScript expressions" as stated here .但是, h1= title
中的缓冲代码仍然是“已评估、转义、缓冲...”,并且“支持 JavaScript 表达式的全部范围”,如此处所述。
So what is the difference?那么区别是什么呢? I can't figure it out.我想不通。
From Buffered Code section in the docs :从文档中的缓冲代码部分:
Buffered code starts with
=
.缓冲代码以=
开头。 It evaluates the JavaScript expression and outputs the result.它评估 JavaScript 表达式并输出结果。 For security, buffered code is first HTML escaped.为了安全起见,缓冲代码首先被 HTML 转义。
From String Interpolation, Escaped section in the docs :来自文档中的字符串插值,转义部分:
The code in between
#{
and}
is evaluated, escaped, and the result buffered into the output of the template being rendered.#{
和}
之间的代码被评估、转义,并将结果缓冲到正在呈现的模板的 output 中。This can be any valid Javascript expression, so you can do whatever feels good.这可以是任何有效的 Javascript 表达式,因此您可以做任何感觉良好的事情。
So, they both:所以,他们俩:
Ie they both do the same things.即他们都做同样的事情。 Which one to use then?那该用哪一个呢? My gut says:我的直觉说:
Example:例子:
// Normal JS variables
- const name = 'John'
- const greeting = `Hello ${name}!`
// Buffered code
p= greeting // 1
p= 'Hello ' + name + '!' // 2
p= `Hello ${name}!` // 3
// Interpolation
p Hello #{name}! // 4
p #{greeting} // 5
p #{'Hello ' + name + '!'} // 6
p #{`Hello ${name}!`} // 7
// Output in all cases:
<p>Hello John!</p>
Notice that numbers 3 and 7 use template literals .请注意,数字 3 和 7 使用模板文字。 Not to be confused with Pug's string interpolation (numbers 4–7).不要与 Pug 的字符串插值(数字 4-7)相混淆。
In my opinion:在我看来:
#{
and }
, so you might as well use buffered code for clarity.数字 5-7 是有效的,但可能有点不必要——这些行除了#{
和}
中的 JS 表达式之外不包含任何其他内容,因此为了清楚起见,您不妨使用缓冲代码。 (But you might prefer them, and that's fine. This is a matter of personal preference.) (但您可能更喜欢它们,这很好。这是个人喜好问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.