pugの記法(HTML)まとめ
自分のはてなブログのテーマ開発にてpugを使っているが、なかなか慣れず、作業するたびに公式Documentを漁っている。
そこでこの用途でよく使う、pugの基本的な記法についてまとめた。
テンプレートエンジンpug
Pug is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. For bug reports, feature requests and questions, open an issue. For discussion join the chat room.
https://github.com/pugjs/pug
本記事は2020.12.29時点の公式サイトの情報を引用している。
Plain Text
Inline in a Tag
行の先頭の文字列がタグになり、空白スペースの後ろはタグに含まれるテキストとなる。
HTMLタグを文中に含めても良い。
p This is plain old <em>text</em> content.
<p>This is plain old <em>text</em> content.</p>
Block in a Tag
インデントすると、タグを階層化できる。
div
p This text belongs to the paragraph tag.
<div>
<p>This text belongs to the paragraph tag.</p>
</div>
応用
文中のHTMLタグは #[
]
で置き換えても良い。
また、タグの後ろに :
を配置すると、複数行を1行の記述にまとめられる。
p: span This is plain old #[em text] content.
<p><span>This is plain old <em>text</em> content.</span></p>
Piped Text
コード上で改行すると、そのままだと別のタグと認識されてしまう。
|
を使うと改行できる。
p
| The pipe always goes at the beginning of its own line,
| not counting indentation.
<p>The pipe always goes at the beginning of its own line,
not counting indentation.</p>
1行の中で複数タグを指定するのにも役立つ。
p
| You put the em
em pha
| sis on the wrong syl
em la
| ble.
<p>You put the em<em>pha</em>sis on the wrong syl<em>la</em>ble.</p>
Whitespace Control
本文なしの |
を配置するとwhitespaceを付与できる。
p
| Don't
|
button#self-destruct touch
|
| me!
<p>Don't
<button id="self-destruct">touch</button>
me!</p>
Attributes
タグに(
)
を連結し、属性を中に記述する。区切りは空白スペースかカンマ。
a(href='//google.com') Google
a(class='button' href='//google.com') Google
a(class='button', href='//google.com') Google
<a href="//google.com">Google</a>
<a class="button" href="//google.com">Google</a>
<a class="button" href="//google.com">Google</a>
Unescaped Attributes
属性の文字列はセキュリティ対策でエスケープされるが、必要な時は =
の代わりに !=
を使うことで回避できる。
div(escaped="<code>")
div(unescaped!="<code>")
<div escaped="<code>"></div>
<div unescaped="<code>"></div>
Class Literal, ID Literal
タグに.
#
を連結すると、クラスやIDを付与する。
タグの指定がなければ自動で <div>
になる
a.button
.content
a#main-link
#content
<a class="button"></a>
<div class="content"></div>
<a id="main-link"></a>
<div id="content"></div>
Comments
//
でコメントアウトできる。 <!-- --->
とそのまま書いても良い。
//-
にすると、レンダリングされたHTMLでは表示しない。
// just some paragraphs
p foo
p bar
//- will not output within markup
p foo2
p bar2
<!-- just some paragraphs-->
<p>foo</p>
<p>bar</p>
<p>foo2</p>
<p>bar2</p>
Block Comments
インデントすれば良い。
body
//-
Comments for your template writers.
Use as much text as you want.
//
Comments for your HTML readers.
Use as much text as you want.
<body>
<!--Comments for your HTML readers.
Use as much text as you want.-->
</body>
Discussion