在Laravel中遇到这么一个问题。我们使用了Blade模板,并创建一个layout作为通用的模板。将子页面作为yield输出:

<!-- store in resource/view/layout.blade.php -->
<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 5 - @yield('title')</title>

        <link rel="stylesheet" href="./style/page.css">
        <script src="./js/jquery.min.js"></script>
        <script src="./js/bootstrap.min.js"></script>
    </head>
    <body>
        <header>
        </header>
 
        <section>
            @yield('content')
        </section>
 
        <footer>
        </footer>
 
    </body>
</html>
<!-- store in resource/view/index.blade.php -->
@extends('layout')
 
@section('title', 'test')
 
@section('content')
<style>
    .pageText {
       font-color : #00ff00;
    }
</style>
 
<div>
    Some Child Page
</div>
 
@endsection

 

为了照顾不同的子页面,就需要在layout中把需要的js和css都加入进来,这样效率低且代码可读性较差,当我们在不同的子页面使用不同的css时,所有CSS就会和section参杂在一起,因此我们可以使用parent标记。

<!-- store in resource/view/layout.blade.php -->
<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 5 - @yield('title')</title>
     @section('style')
        <link rel="stylesheet" href="./style/page.css">
     @show
@section('script') <script src="./js/jquery.min.js"></script> <script src="./js/bootstrap.min.js"></script>
@show
</head> <body> <header> </header> <section> @yield('content') </section> <footer> </footer> </body> </html>
<!-- store in resource/view/index.blade.php -->
@extends('layout')
 
@section('title', 'test')
 
@section('style')
@parent
<style>
    .pageText {
       font-color : #00ff00;
    }
</style> 
@endsection

@section('content')
<div>
    Some Child Page
</div>
 
@endsection

这样就可以解决问题了。

posted on 2016-03-22 23:30  小虾ff  阅读(8687)  评论(0编辑  收藏  举报