【问题标题】:Child partial not injecting styles into its parent blade layout子部分未将样式注入其父刀片布局
【发布时间】:2020-04-21 03:26:14
【问题描述】:

我有一个需要一些自定义 js 和样式的部分子视图。这个孩子是整个应用程序中唯一使用它的视图。它很复杂,所以 JS 被分解成自己的文件。

我尝试将脚本和样式“注入”到父布局according to the docs 中,但它似乎不起作用。我已经厌倦了这些部分中@parent@@parent 的组合。我尝试将主要布局,@yield('scripts') @yield('styles') 更改为 @section('scripts')@show

我错过了什么?这甚至可能吗?

ma​​in.blade.php(为简洁起见)

<head>
    @include('apps.includes.styles')

    @yield('styles')//a place for custom style
</head>
<body>
@yield('content')

@include('apps.includes.scripts')
@yield('scripts') //a place for custom scripts
</body>

create.blade.php

@extends('layouts.main')
@section('styles')@endsection
@section('scripts')@endsection
@section('content')
    <div>
      @include('partials._toolbar')
    </div>
@endsection

_toolbar.blade.php

@section('styles')
    @parent
    <script src="{{asset('assets/css/mystyle.css')}}"></script>
@endsection

@section('scripts')
    @parent
    <script src="{{asset('assets/js/myjs.js')}}"></script>
@endsection

<section>
// my toolbar html code
</section>

【问题讨论】:

    标签: php laravel laravel-5 laravel-blade laravel-6


    【解决方案1】:

    您尝试做的事情是不可能的。您只能通过扩展布局来填充部分,而不是通过包含它。相反,为您的样式使用 stack

    toolbar.blade.php

    @push('styles')
        <script src="{{asset('assets/css/mystyle.css')}}"></script>
    @endpush
    

    ma​​in.blade.php

    <head>
        @include('apps.includes.styles')
    
        @stack('styles')
    </head>
    

    您可以在official documentation 中阅读有关堆栈的更多信息。

    【讨论】:

    • 那么@parent 是干什么用的?
    • 用于扩展节的内容。但仅当使用@extends('parent.layout') 扩展 布局时。与 include 相比,这是一个不同的视角。扩展是自下而上的过程,而包含是自上而下的。
    • @push 有效。我必须再等 8 分钟才能接受答案。我稍后会回来做那件事。
    猜你喜欢
    • 2016-05-16
    • 2014-06-28
    • 2013-02-25
    • 2015-08-14
    • 2023-04-08
    • 2019-10-03
    • 2018-09-16
    • 2017-01-27
    • 2016-08-09
    相关资源
    最近更新 更多