Laravel 如何在Blade模板中能夠根據不同的子頁面附加不同的js和CSS


在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

這樣就可以解決問題了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM