Home  >  Q&A  >  body text

Unable to successfully execute JavaScript code within Blade

I have a file called all.blade.php that looks like this:

@component('admin.layouts.content' , ['title' => 'example file'])
   @slot('breadcrumb')
        <li class="breadcrumb-item active">Example File</li>
   @endslot
   ...
@endcomponent

@push('scripts')
    <script>
        Swal.fire({
            title: 'Do you want to save the changes?',
            showDenyButton: true,
            showCancelButton: true,
            confirmButtonText: 'Save',
            denyButtonText: `Don't save`,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                Swal.fire('Saved!', '', 'success')
            } else if (result.isDenied) {
                Swal.fire('Changes are not saved', '', 'info')
            }
        })
    </script>
@endpush

This is content.blade.php:

@extends('admin.master')

@section('content')
   {{ $slot }}
@endsection

This is master.blade.php:

<!DOCTYPE html>
  <html>
     <head>
        ...
        @stack('scripts')
     </head>
     <body>
        @yield('content')
     </body>
   </html>

Now the problem is @push('scripts') ... @endpush doesn't work and doesn't show the sweet alert message.

So what’s the problem here? How can I solve this problem and call @component and @push together on blade?

P粉476046165P粉476046165260 days ago412

reply all(2)I'll reply

  • P粉681400307

    P粉6814003072024-02-26 14:09:17

    Try Ctrl U Check if the component is rendered to its position. Also note that if you are using the Swallibrary JS library, the actual Swallibrary code is loaded before the fire() function is called.

    Finally please check the browser console options to determine if it is some JS error and not a Blade error.

    reply
    0
  • P粉494151941

    P粉4941519412024-02-26 12:58:45

    Replace the order of @push and @component

    @push('scripts')
        
    @endpush
    
    @component('admin.layouts.content' , ['title' => 'example file'])
       @slot('breadcrumb')
            
       @endslot
       ...
    @endcomponent
    

    Another option is to convert the main to a component

    
    
      
         
            ...
            {{ $scripts ?? '' }}
         
         
            {{ $slot }}
         
       
    

    and convert content into components

    
    
        
           {{ $scripts ?? '' }}
        
        {{ $slot }}
    
       
    
    

    Then you can write all.blade.php as

    
        
            
        
        

    All

    reply
    0
  • Cancelreply