アジェンダ
- テンプレート構造
- Viewが表示される流れ
- テンプレート類
- _Layout.cshtml
- _ViewStart.cshtml
- 共通パーツ
テンプレート構造
├ Views
├ Shared (共通パーツ格納ディレクトリ)
│ ├ _Layout.cshtml(アプリの既定のレイアウト)
│ ├ _Header.cshtml
│ └ _Footer.cshtml
└ _ViewStart.cshtml (各ビューの前に実行する処理を記載する)
Viewが表示される流れ
- /Views/_ViewStart.chtmlが読み込まれる
- /Views/Shared/_Layout.chtmlが読み込まれる(1.で指定しているから)
3.の_Layout.chtml中の@RenderBody()が呼ばれる(2. に記述されているから)
@RenderBody()はテンプレートに1箇所のみ - 必要に応じて@RenderSection()が呼ばれる
@RenderSection()は複数箇所でも可
テンプレート類
_Layout.cshtml
アプリの既定のレイアウト。
ファイル名の先頭に「_(パーシャル)」を付ける。
_layout.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
@RenderBody() とは
このテンプレートを使ったページの本体を出力する。
@RenderSection()とは
@RenderSection(セクション名, required: 必須かどうか)のように引数を用いて、メインのボディ部分以外も、カスタマイズできるようにしている。
具体的に言うと。。
■レイアウトでscriptsセクションを呼び出すように指定して
_layout.html
@RenderSection("scripts", required: false)
■各ページでscriptsセクションを用意してあげる。
index.html
@section scripts{
<script type="text/javascript">
$(function(){
//index.htmlで使うjsの処理を記述
});
</script>
}
_ViewStart.cshtml
最初に実行する処理を記載する。
_ViewStart.html
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}