2014-02-15 53 views
27

試圖將單獨的標題和元描述應用於我的網站頁面,但我不確定我嘗試的方式是否非常乾淨。Laravel 4如何使用刀片母版頁將標題和元信息應用於每個頁面

master.blade.php

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>{{ $title }}</title> 
    <meta name="description" content="{{ $description }}"> 
</head> 

個人頁面

@extends('layouts.master') 
<?php $title = "This is an individual page title"; ?> 
<?php $description = "This is a description"; ?> 

@section('content') 

我覺得這是把工作做一個快速和骯髒的方式,是有一個更清潔的方式?

回答

85

這工作,以及:

master.blade.php

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>@yield('title')</title> 
    <meta name="description" content="@yield('description')"> 
</head> 

個人頁面

@extends('layouts.master') 

@section('title') 
    This is an individual page title 
@stop 

@section('description') 
    This is a description 
@stop 

@section('content') 

,或者如果你想縮短一些更多,或做這個:

個人頁面

@extends('layouts.master') 

@section('title', 'This is an individual page title') 
@section('description', 'This is a description') 

@section('content') 
+2

提供示例這應該是被接受的答案。 – roastedtoast

+1

這是一個更好的答案。 –

+0

我會在元標記周圍放置@if(!empty($ description)).. @ endif'。只是爲了避免具有空描述的元標籤。 – Adam

8

這應該工作:

@extends('layouts.master') 
<?php View::share('title', 'title'); ?> 

... 

你也可以這樣做:

@extends('views.coming-soon.layout', ['title' => 'This is an individual page title']) 
+0

有趣的是,什麼是'查看::份額();'?我可以爲元描述做同樣的事嗎? –

+0

這些變量被實例化用於佈局或子視圖中需要的任何位置。 –

+0

雖然這個方法似乎有效(感謝Antonio,我不知道你可以通過'@ extends'傳遞一個數組來傳遞鏈上的變量),但我有一種感覺,在這些情況下,總體思路是'擴展'一個部分(參見[文檔](http://laravel.com/docs/templates#blade-templating)中的'@ section'和'@ parent'),也就是說,這在'導航'例如頁面標題,尤其是元描述(因爲必須使用HTML屬性中的刀片語法,這種語法感覺很髒) – alexrussell

1

沒有人認爲最好的方法是創建你自己的門面與類(網站::標題() ,Site :: description等)和mutators(通過Str :: macro)自動檢查標題,描述等格式是否正確(最大長度,添加類別,默認值,分隔符等)並將數據克隆到其他字段(title = > og:title,description => og:description)如果有必要?

+1

您可以用簡單易用的新手友好的術語來擴展它嗎? –

+1

不,我不要認爲這是最好的方法,我還沒有設計一個Laravel 4站點,需要一個正式的外觀來進行視圖變量管理。我明白你提到的因素的重要性,但我認爲這些是專門的需求,應該根據具體情況進行處理。 – bishop

+0

當您正在進行大規模應用程序時,這是一個不錯的方法。 –

2

真的建議是:

https://github.com/artesaos/seotools

您將信息傳遞到視圖所需要的內容

SEOTools::setTitle($page->seotitle); 
SEOTools::setDescription($page->seodescription); 
相關問題