如何在Laravel的Blade模板中使用@push指令

35

我需要一个脚本,仅在一个页面上运行。并且它应该在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')吗?


是的,这就是推和栈的使用方式。它不起作用吗? - David Hallberg Jönsson
@DavidHallbergJönsson,在index.blade(主视图)中无法工作。我已经包含了所有的js,如下所示: `<script type="text/javascript" src="{{ URL::asset ('js/jquery.js') }}"></script><script type="text/javascript" src="{{ URL::asset ('js/plugins.js') }}"></script> @push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script> @endpush 然后在子视图中,我写了以下代码:@stack('custom-scripts')` - kuka
2个回答

60
你只需要将它反过来,@push 应该在子视图中使用,用于将内容推送到父级的 @stack 指令。

因此,你的 index.blade.php 应该有一个:

@stack('custom-scripts')

你的子视图:

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

您也可以像这样在@section中使用@parent指令:

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


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

如果您需要更多信息,我建议您查看文档。希望这能帮到您。


1

使用@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

是的,但如果您正在循环/递归中推送脚本或由于某种原因多次推送该特定部分,则需要使用@once,然后once将确保仅添加该脚本一次。否则,您不需要它。 - Furqan Freed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接