如何在 blade 模板 laravel 中使用指令 @push

how to use directive @push in blade template laravel

我只需要一页上的脚本。它应该在 jQuery 之后加载。 我试过 index.blade

<script type="text/javascript" src="{{ URL::asset ('js/jquery.js') }}"></script>
@push('custom-scripts')
    <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script>
@endpush

然后我应该在我看来使用@stack('custom-scripts')?

你只需要以相反的方式进行,@push 意味着在 child 视图中,它将内容推送到 parent @stack 指令。

所以你的 index.blade.php 应该有:

@stack('custom-scripts')

你的 child 观点:

@push('custom-scripts')
    <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script>
@endpush

您还可以像这样将 @parent 指令与 @section 一起使用:

//index.blade.php
@yield('scripts')


//child.blade.php
@section('scripts')
    @parent
    <!-- The rest of your scripts -->
@endsection

如果您需要更多信息,我建议您查看 documentation。希望对你有帮助。

使用 @once 也可能有助于防止脚本被多次执行。您可以将根视图定义为在 <head> 标记末尾和 <body> 标记末尾处放置脚本的固定位置:

app.blade.php:

<html>
  <head>
    <title>Website</title>
    @stack('head-scripts')
  </head>

  <body>
    <main>@yield('content')</main>

  @stack('body-scripts')
  </body>
</html>

home.blade.php:

@extends('layouts.app')
@section('content')
    <div>Hello World</div>

    @push('body-scripts')
        @once
        <script src="https://unpkg.com/imask"></script>
        @endonce
    @endpush
@endsection