how to use directive @push in blade template laravel
Asked Answered
H

2

38

I need script only on one page. and it should load after jQuery. I tried in 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

and then I should use @stack('custom-scripts') in my view?

Hardpressed answered 21/6, 2017 at 11:1 Comment(2)
Yes, this how push and stack is used. Is it not working?Otto
@DavidHallbergJönsson , is not working. in index.blade (main view) I include all js. like <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 and then in a child view I wrote @stack('custom-scripts')Hardpressed
C
63

You just need to make that the opposite way, @push is meant to be in the child view, which is pushing content to the parent @stack directive.

So your index.blade.php should have a:

@stack('custom-scripts')

And your child view:

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

You can also use @parent directive with @section like this:

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


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

If you need more info I'd recommend you to check the documentation. Hope this helped you.

Catalyst answered 21/6, 2017 at 12:57 Comment(0)
H
1

Using @once might be also helpful for someone to prevent scripts from being executed more than once. You can define your root view to have a fixed place for scripts that should go at the end of the <head> tag and at the end of the <body> tag:

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
Heinrike answered 6/9, 2021 at 16:12 Comment(1)
yup but @once you need if you are pushing script inside loop / recursion or for some reason you are pushing that specific section multiple time then once will make sure to add that script only once. else you do not need that.Mechanical

© 2022 - 2024 — McMap. All rights reserved.