插值
Pug 提供了各种不同的插值需求的操作符。
字符串插值,转义
考虑以下模板的局部变量的放置:title
、author
和 theGreat
。
xxxxxxxxxx
- 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}
xxxxxxxxxx
<h1>On Dogs: Man's Best Friend</h1> <p>Written with love by enlore</p> <p>This will be safe: <span>escape!</span></p>
title
遵循评估模板局部的基本模式,但 #{
和 }
之间的代码将被评估、转义,并将结果缓冲到要呈现的模板的输出中。
这可以是任何有效的 Javascript 表达式,因此您可以做任何感觉良好的事情。
xxxxxxxxxx
- var msg = "not my inside voice"; p This is #{msg.toUpperCase()}
xxxxxxxxxx
<p>This is NOT MY INSIDE VOICE</p>
Pug 足够聪明,可以找出表达式结束的位置,因此您甚至可以包含 }
而无需转义。
xxxxxxxxxx
p No escaping for #{'}'}!
xxxxxxxxxx
<p>No escaping for }!</p>
如果您需要包含一个原义的 #{
,您可以转义它,或使用插值。(如此元!)
xxxxxxxxxx
p Escaping works with \#{interpolation} p Interpolation works with #{'#{interpolation}'} too!
xxxxxxxxxx
<p>Escaping works with #{interpolation}</p> <p>Interpolation works with #{interpolation} too!</p>
字符串插值,未转义
您不必保持安全。您也可以将未转义的值缓冲到模板中。
xxxxxxxxxx
- var riskyBusiness = "<em>Some of the girls are wearing my mother's clothing.</em>"; .quote p Joel: !{riskyBusiness}
xxxxxxxxxx
<div class="quote"> <p>Joel: <em>Some of the girls are wearing my mother's clothing.</em></p> </div>
警告
请记住,如果内容来自您的用户,则将未转义的内容缓冲到模板中可能会非常危险。永远不要信任用户输入!
标签插值
插值不仅适用于 JavaScript 值,也适用于 Pug。只需使用标签插值语法,如下所示
xxxxxxxxxx
p. 这是一个非常长且无聊的段落,跨越多行。突然出现了一个 #[strong 强烈措辞的短语],无法 #[em 忽略]。p. 这是一个带有属性的插值标签示例: #[q(lang="es") ¡Hola Mundo!]
xxxxxxxxxx
<p>这是一个非常长且无聊的段落,跨越多行。突然出现了一个 <strong>强烈措辞的短语</strong>,无法 <em>忽略</em>.</p> <p>这是一个带有属性的插值标签示例: <q lang="es">¡Hola Mundo!</q></p>
你可以通过在 Pug 中内联编写 HTML 标签来实现相同的效果……但是,这样编写 Pug 的意义何在?将内联 Pug 标签声明包装在 #[
和 ]
中,它将被评估并缓冲到其包含标签的内容中。
空格控制
标签插值语法对于内联标签特别有用,其中标签前后的空格很重要。
但是,默认情况下,Pug 会删除所有标签前后的空格。查看以下示例
xxxxxxxxxx
p | 如果我不使用标签插值来编写段落,则类似 strong strong | 和 em em | 的标签可能会产生意外的结果。p. 如果我这样做,空格将 #[strong 被尊重],并且 #[em 所有人] 都很高兴。
xxxxxxxxxx
<p>如果我不使用标签插值来编写段落,则类似<strong>strong</strong>和<em>em</em>的标签可能会产生意外的结果。</p> <p>如果我这样做,空格将 <strong>被尊重</strong>,并且 <em>所有人</em> 都很高兴。</p>
请参阅 纯文本 页面中的空格部分,以了解有关此主题的更多讨论。