Interpolation

更新日: 2018-09-10

文字列補間

Pugは様々な方法で文字列補間(変数展開)することができます。


エスケープ

以下のテンプレート変数titleauthortheGreatを 配置するとします。

- 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}
<h1>On Dogs: Man's Best Friend</h1>
<p>Written with love by enlore</p>
<p>This will be safe: &lt;span&gt;escape!&lt;/span&gt;</p>

titleは決められたパターンに従って、 #{}のコードを評価し、エスケープし、 結果はレンダリングされたページに反映されます。

変数はJavaScript式の可能性もあります、その場合は以下のように指定します。

- var msg = "not my inside voice";
p This is #{msg.toUpperCase()}
<p>This is NOT MY INSIDE VOICE</p>

Pugはとても賢いので、式の終了}をエスケープする必要はありません。

p No escaping for #{'}'}!
<p>No escaping for }!</p>

もし#{を使いたければ、エスケープするか文字列補間する必要があります。(まさにメタ!)

p Escaping works with \#{interpolation}
p Interpolation works with #{'#{interpolation}'} too!
<p>Escaping works with #{interpolation}</p>
<p>Interpolation works with #{interpolation} too!</p>

非エスケープ

安全性を考慮なら、以下のように指定することでエスケープしません。

- var riskyBusiness = "<em>Some of the girls are wearing my mother's clothing.</em>";
.quote
  p Joel: !{riskyBusiness}
<div class="quote">
  <p>Joel: <em>Some of the girls are wearing my mother's clothing.</em></p>
</div>

注意

エスケープしていないコンテンツをテンプレートに含めると、ユーザーからの更新によって、危険にさらされる可能性があります。ユーザーの入力を信頼しないでください!


タグ補間

Pugの文字列補間はJavaScriptだけではありません。Pug自体の補間も同様です。

p.
  This is a very long and boring paragraph that spans multiple lines.
  Suddenly there is a #[strong strongly worded phrase] that cannot be
  #[em ignored].
p.
  And here's an example of an interpolated tag with an attribute:
  #[q(lang="es") ¡Hola Mundo!]
<p>This is a very long and boring paragraph that spans multiple lines.
  Suddenly there is a <strong>strongly worded phrase</strong> that cannot be
  <em>ignored</em>.</p>
<p>And here's an example of an interpolated tag with an attribute:
  <q lang="es">¡Hola Mundo!</q></p>

PugでもHTMLタグと同じようにインラインで書くことができます。 どのように書くのでしょうか? Pugのタグ補間は#[]を使って囲みます。 するとタグとして評価され、レンダリングされます。


前後のスペース

タグ補間はタグ前後のスペースが必要な場合に便利です。

デフォルトでは前後のスペースを除去します。 以下の例を見て下さい。

p
  | If I don't write the paragraph with tag interpolation, tags like
  strong strong
  | and
  em em
  | might produce unexpected results.
p.
  If I do, whitespace is #[strong respected] and #[em everybody] is happy.
<p>If I don't write the paragraph with tag interpolation, tags like<strong>strong</strong>and<em>em</em>might produce unexpected results.</p>
<p>If I do, whitespace is <strong>respected</strong> and <em>everybody</em> is happy.</p>

このトピックについてはスペース管理を参照して下さい。


© 2017 pugjs.org Released under the MIT license

このコンテンツはpugドキュメントを翻訳/改変したものです。