ふたりはララベル (Laravel PHP Framework)

PHPフレームワークのLaravelの体験記を書いていきます。こんなタイトルのブログですが萌え系アニメは一秒たりとも観たことがありません。

Laravelではページのタイトルをどうつければいいか?

例えば「無題のドキュメント」というタイトルをつけたいとして…。

方法1:Blade上にタイトルを書く

以下のようにBladeを設定する。

@extends('layout.default')

@section('title')
無題のドキュメント
@stop

@section('content')
<p>Hello World.</p>
@stop

layout.defaultから呼び出される「default.blade.php」には

<title>
	@section('title')
	Tutorial
	@show
</title>

と書く。

方法2:コントローラーにタイトルを書く

コントローラー上でタイトルを設定したい場合はこの方法。

public function index() {

  $title = '無題のドキュメント';

  return View::make('hello.index')->with('title', $title);
}

Blade側は

<title>{{ $title }}</title>

となる。

方法3:コントローラーでWithを使わずにタイトルを書く

Withを使いたくない場合はこの方法。

class HelloController extends \BaseController {

  protected $layout = 'layouts.default';

  public function index() {

    $this->layout->title = '無題のドキュメント';

    $this->layout->content = View::make('hello.index');
  }

Blade側は同じく

<title>{{ $title }}</title>

となる。

この場合、route.phpだけwithを使ったほうがいいかも。

Route::get('/', function()
{
    
	return View::make('index')->with('title','TOP画面');
});