ビューの基本
前章で、ルーティングの基本について学んでいただきました。
ルーティングは 「あるURLに特定のメソッド(get, postなど)でアクセスしたら、どんな文字列をレスポンスとして返すのか?」 を決めるシンプルな仕組みです。
では、ルーティングの仕組みだけを使って、 本格的なHTML5の文書を送信してみましょう。
web.php
Route::get('/non_view_sample', function () {
return '
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ルーティングのみでHTMLを返す。</title>
</head>
<body>
<h1>Laravelの練習</h1>
<p>ルーティングのファイルのみで、HTML全体を返すと長くなります。</p>
</body>
</html>
';
});
上記を追記したら http://localhost/non_view_sample にアクセスしてみましょう。
正しくHTMLが表示されていればOKです。
Viewの意義
上記のように、ルーティングのファイルに直接HTMLを書いていっても 簡単なwebサイトは構築できます。 しかし、容易に想像がつくように、このままたくさんのルーティングを追加していけば すぐに web.php は大量のHTMLで溢れた非常に読みにくい長大なファイルになってしまいます。
ここで用いられるのが view の仕組みです。
Viewファイルの配置場所
Viewファイルの配置場所は
sample_app/resources/views/
の中です。
現時点では welcome.blade.php というファイルだけ存在しているので、中身をのぞいてみましょう。
welcome.blade.php
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Raleway', sans-serif;
font-weight: 100;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 12px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
</style>
</head>
<body>
<div class="flex-center position-ref full-height">
@if (Route::has('login'))
<div class="top-right links">
@auth
<a href="{{ url('/home') }}">Home</a>
@else
<a href="{{ route('login') }}">Login</a>
<a href="{{ route('register') }}">Register</a>
@endauth
</div>
@endif
<div class="content">
<div class="title m-b-md">
Laravel
</div>
<div class="links">
<a href="https://laravel.com/docs">Documentation</a>
<a href="https://laracasts.com">Laracasts</a>
<a href="https://laravel-news.com">News</a>
<a href="https://forge.laravel.com">Forge</a>
<a href="https://github.com/laravel/laravel">GitHub</a>
</div>
</div>
</div>
</body>
</html>
ちょっと長いですが、よく内容を確認してみると、 一番最初にアクセスした時のLaravelのスタートページの内容であることがわかるでしょう。
初期状態のweb.phpでは
web.php
<?php
(コメントを省略)
Route::get('/', function () {
return view('welcome');
});
と書かれていて、まさにこのwelcomeというviewファイルの内容が、
(Docker Toolboxの場合は http://(dockerのipアドレス) )
にアクセスした時に表示されていたのです。