【问题标题】:how to use directive @push in blade template laravel如何在刀片模板 laravel 中使用指令 @push
【发布时间】:2017-11-24 05:58:28
【问题描述】:

我只需要在一页上的脚本。它应该在 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 和 stack 的使用方式。它不工作吗?
  • @DavidHallbergJönsson ,不工作。在 index.blade (主视图)中,我包含了所有 js。喜欢&lt;script type="text/javascript" src="{{ URL::asset ('js/jquery.js') }}"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ URL::asset ('js/plugins.js') }}"&gt;&lt;/script&gt; @push('custom-scripts') &lt;script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"&gt;&lt;/script&gt; @endpush 然后在子视图中我写了@stack('custom-scripts')

标签: jquery laravel dom include blade


【解决方案1】:

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

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

@stack('custom-scripts')

你的孩子的看法:

@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。希望这对您有所帮助。

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2015-10-13
      • 2016-12-18
      • 2013-04-29
      • 2021-07-11
      • 1970-01-01
      • 2019-11-03
      • 2021-11-21
      相关资源
      最近更新 更多