Transclude
transclude, section
説明
{{ transclude '/path/to/layout' }}
{{ section name }}
{{ end section name }}
{{ transclude }}を書くと、テンプレートはレイアウト(親テンプレート)を継承します。親は名前付きの{{ section }}ブロックを宣言し、子がその中身を埋めます。親は、それぞれのセクションを宣言した場所に出力します。
- 親のセクションは、中身を入れる場所です。親に書いた中身はデフォルトで、子がそのセクションを定義しないときに出力されます。
- 子のセクションは、中身を定義します。セクション名は親と同じにします。
- 継承は何段階でもできます。子は、親が宣言したセクションも、さらに上のレイアウトが宣言したセクションも埋められます。
{{ transclude }}は1つのテンプレートに1つです。パスはインクルードのルールに従います。'/template/siteframe'のように、/から始まるパスを使ってください。親が見つからないときは、タグの行番号付きでFegg\Template\TemplateExceptionを投げます。- セクションは
{{ end section name }}(推奨)か{{ end section }}で閉じます。
注意点がいくつかあります。
- 子テンプレートで
{{ section }}の外にあるテキストは、親レイアウトより前に出力されます。すべてセクションの中に書きます(セクションの外のテキストはfegg-cli template:lintが警告します)。 - セクションは関数として実行されます。セクションの中に書いた
{{ assign }}、{{ include head }}、{{ include foot }}は、そのセクションの中にしか効きません。{{ transclude }}と並べて、テンプレートの最上位に書きます。 - 親が宣言していないセクションは、子が定義した場所に出力されます。
例
site/template/main/tpl/template/siteframe.tpl
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>{{ $site.title }}</title>
</head>
<body>
<main>
{{ section contents }}
<p>Default content</p>
{{ end section contents }}
</main>
</body>
</html>
site/template/main/tpl/index.tpl
{{ transclude '/template/siteframe' }}
{{ section contents }}
<p>This is the index content.</p>
{{ end section contents }}
Output
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Example Inc.</title>
</head>
<body>
<main>
<p>This is the index content.</p>
</main>
</body>
</html>
多段階の継承
site/template/main/tpl/base.tpl
<html>
<body>
{{ section header }}<header>Default header</header>{{ end section header }}
{{ section body }}{{ end section body }}
</body>
</html>
site/template/main/tpl/layout/two_columns.tpl
{{ transclude '/base' }}
{{ section body }}
<div class="l-columns">
<aside>Menu</aside>
<div class="l-columns__main">
{{ section main }}{{ end section main }}
</div>
</div>
{{ end section body }}
site/template/main/tpl/news/detail.tpl
{{ transclude '/layout/two_columns' }}
{{ section header }}<header>News</header>{{ end section header }}
{{ section main }}
<p>This is the news content.</p>
{{ end section main }}
Output (whitespace simplified)
<html>
<body>
<header>News</header>
<div class="l-columns">
<aside>Menu</aside>
<div class="l-columns__main">
<p>This is the news content.</p>
</div>
</div>
</body>
</html>
news/detailは、2段階上のbaseで宣言されたheaderと、直接の親が宣言したmainを埋めています。