jquery 如何在blade模板laravel中使用directive @push

sg3maiej  于 2023-05-17  发布在  jQuery
关注(0)|答案(2)|浏览(177)

我只需要一页上的脚本。它应该在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')?

toe95027

toe950271#

您只需要以相反的方式进行设置,@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

如果你需要更多的信息,我建议你检查文档。希望这对你有帮助。

fslejnso

fslejnso2#

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

相关问题