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