テンプレートを継承してテーマを最適化
Posted in: a-blog cmsテンプレートの継承
a-blog cms Ver.2.8 から追加された新機能「テンプレートの継承」。テーマの中でファイルを継承し、指定した範囲を上書きできるとのこと。春合宿のハンズオン資料を参考に試してみます。
![]()
G: @extendsを使ってテンプレートを最適化してみよう | 2018春合宿 | ハンズオン | a-blog cms developer
a-blog cms developer
Ver. 2.8.0 よりテンプレートを継承できる機能が追加されました。 このハンズオンでは、継承機能(@extends)を使ってテンプレートをわかりやすくて管理しやすい形にしていきます。 1. ハン...
ファイルの読み込み記述を @include に書き換え
これまでのファイル読み込み記述 <!--#include file="/path/to/file" --> を @include("/path/to/file") に変更したら、ソースコードがぐんと見やすくなった感じがします。
継承元テンプレートを作成
ベースになるテンプレートを作成します。例えば/layout/base.html。このファイルを継承します。さらに、ソース内の任意の範囲を @section ~ @endsection で囲み、セクション名をつけて設定。継承する際に追加・変更など上書きできるようになります。
<!DOCTYPE html>
<html lang="ja">
<head>
@section(head-meta)
@include("/include/head/meta.html")
@endsection
@section(head-link)
@include("/include/head/link.html")
@endsection
@section(head-js)
@include("/include/head/js.html")
@endsection
</head>
<body>
<header>
@section(header)
<h1><a href="%{BASE_URL}">%{BLOG_NAME}</a></h1>
@endsection
</header>
<main>
@section(main)
@include("/include/entry/body.html")
@endsection
</main>
<aside>
@section(aside)
@include("/include/parts/search.html")
@endsection
</aside>
<footer>
@section(footer)
<p>© %{DOMAIN}</p>
@endsection
</footer>
</body>
</html>継承してモジュールを追加してみる
base.html を index.html に読み込みます。さらに任意の @section ~ @endsection 内を上書きします。以下は aside セクションにカテゴリーリストを追加する内容です。
// 継承元テンプレートの読み込み
@extends("/layout/base.html")
//上書きする部分
@section(aside)
@include("/include/parts/search.html")
@include("/include/category/list.html")
@endsectionindex.html のソースはこれだけ。
またbase.html は index.html の親テンプレートに当たるので、最初から設定されている @include("/include/parts/search.html") 部分は@parent で参照できる。
@extends("/layout/base.html")
@section(aside)
@parent
@include("/include/category/list.html")
@endsection雑感
構築するウェブサイトの規模などにもよりますが、テンプレートの継承をメインに制作していくと、管理や効率が良さそうだと実感しました。参照元テンプレートは@section@include だらけにしないことがポイントかもしれません。