今回は条件によってheaderの読み込む内容を変更する方法を書きます。
それでは、解説。
○index1.pug
extends _layout.pug
block _addMeta
//-meta
title デモ
meta(name="description", content="")
meta(name="keywords", content="")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
link(rel="stylesheet" href="css/index.css")
block var
- var contents = `header01`;
block mainContents
main(ontouchstart="")
.backgroundBox
.Container
p pugファイルの使い方
○index2.pug
extends _layout.pug
block _addMeta
//-meta
title デモ
meta(name="description", content="")
meta(name="keywords", content="")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
link(rel="stylesheet" href="css/index.css")
block var
- var contents = `header02`;
block mainContents
main(ontouchstart="")
.backgroundBox
.Container
p pugファイルの使い方
<ポイント>
・index1.pugとindex2.pugファイルの違いはblock varの塊部分です。
それぞれ、contentsという変数にheader01とheader02を定義しています。
・pugが実行されると、extends _layout.pugによって、 _layout.pugが適用されます。
○_layout.pug
block var
doctype html
html(lang='ja')
head
meta(charset="utf-8")
include _meta
block _addMeta
body
include _header
block mainContents
include _footer
<ポイント>
・_layout.pugが実行されると、blockとincludeが適用されます。
○_header.pug
//header
header
p テストだよ
if contents == `header01`
p header01を読み込んだよ
if contents == `header02`
p header02を読み込んだよ
<ポイント>
・_headerが読み込まれると、ifによる条件によって、読み込み部分が変わります。
・index1.pugはcontents = header01を定義していたので、header01が読み込まれます。
・index2.pugはcontents = header02を定義していたので、header02が読み込まれます。
このように、変数を定義すれば開発がサクサク進むと思います。
紹介していないその他のpugファイルは過去記事をご覧ください。
今回は以上です。
変数の詳しい内容に関しては下記サイトをご覧ください。個人的にわかりやすいと思いました。
https://necosystem.hirokihomma.com/archives/121/