在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
這樣就可以解決問題了。
