【问题标题】:Load page specific resource(s) using @include使用 @include 加载页面特定资源
【发布时间】:2017-01-29 19:37:05
【问题描述】:

如何使用 Laravel Blade 模板引擎的 @include 加载页面特定资源?

下面是我的Master布局的内容(master.blade.php):

<head>
    @section('styles')
        {{-- Some Master Styles --}}
    @show
</head>
<body>
    {{-- Header --}}
    @section('header')
        @include('header')
    @show

    {{-- Content --}} 
    @section('content')
        {{-- Content for page is extending this view --}}
    @show

    {{-- Footer --}}
    @section('footer')
        @include('footer')
    @show
</body>

在给定的页面中,我以这种方式使用我的主模板:

@extends('master')

@section('styles')
    @parent
    {{-- Page Stylesheet --}}
@endsection

上面的方法是我用来尝试将我的页面特定样式加载到&lt;head&gt; 部分的方法。

它没有按预期正常工作。

我还想使用相同的方法在我的页脚中加载其他特定于页面的资源;我怎样才能有效地做到这一点?

【问题讨论】:

    标签: php laravel blade laravel-blade laravel-5.3


    【解决方案1】:

    你不需要这样做

    @extends('master')
    
    @section('styles')
        @parent
        {{-- Page Stylesheet --}}
    @endsection
    

    在您各自的页面中,以便加载页面特定的样式表。

    您应该为您的 master.blade.php 文件加载特定于页面的样式表,以保持您的代码干燥。

    为此,您需要指定此类页面的路径或预期的 url 格式,然后,要加载适当的样式表。

    您可以在 master.blade.php 文件中这样做:

    @section('styles')
        @if(Request::is('transactions/generate-invoice'))
            @include('generate-invoice-css')
        @elseif(Request::is('transactions/users'))
            @include('users-css')
        @endif
    @show
    

    其中 generate-invoice-css.blade.php 包含您要为可通过 yoursite.com/transactions/generate-invoiceusers-css.blade.php 访问的页面内容加载的样式表, yoursite.com/transactions/users.

    对于给定的模式,如:transactions下的页面的样式表相同,您可以这样做:

    @if(Request::is('transactions*'))
    

    使用通配符*

    要将给定资源加载到页面的&lt;head&gt; 部分以外的位置,只需使用相同的方法并进行适当调整即可。

    要使用 master.blade.php 中的 @include() 加载页面特定资源,请使用此方法(在您的 master.blade.php强>文件)

    @section('styles')
        @include('styles')
    @show
    

    其中 styles.blade.php 应包含您的条件,以便加载满足您的要求的适当资源,其目的如下:

    @if(Request::is('transactions/generate-invoice'))
        @include('generate-invoice-css')
    @elseif(Request::is('transactions/users'))
        @include('users-css')
    @endif
    

    作为您的 styles.blade.php 的内容。

    【讨论】:

    • 感谢@nyedidikeke 的回复。至于包含,我在一个部分中添加了它,因为在 Master 中会有更多的贡献。至于您提到的样式表的加载,这是可行的,但它会嵌入样式表。我希望有一种“更清洁”的方式来解决它,它将样式表添加到头部,就像在加载样式时对布局的扩展所做的那样。这可能不是一个选择,但我正在尝试找出它是否可能。
    • 如果你想在你的&lt;head&gt;部分中,你应该把它包含在你的styles.blade.php中。根据您的问题,您表示将其包括在您的 footer 部分。
    • 根据您上面提交的内容更新了我的答案,改为将您的样式表包含在 &lt;head&gt; 部分中。
    • 好的,我想我只是没有清楚地提出我的问题。我希望每个视图都可以加载它自己的样式表。例如,当包含页脚时,它会导入自己的样式表,但刀片模板会将 与样式表导入的其余部分放在 中。这似乎是页面扩展布局并加载样式表时发生的情况。
    • 你最近的 cmets 建议,也许,这不是我理解的正确方法。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2013-10-23
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多