Skip to content
Advertisement

Laravel, right way to import javascript into Blade Templates

I am using Laravel 5.6. This page did not work for me.

pizza/index.blade.php looks like this:

JavaScript

pizza/table.blade.php:

JavaScript

I get a reference error when I click on the “add_new_pizza” button, onClick=”addPizza()”, addPizza() is not defined. However, I try to import pizza.js in index.blade.php

JavaScript

printing out asset(‘js/components/pizza.js’) returns http://localhost:8080/js/components/pizza.js which looks right to me.

public/js/components/pizza.js looks like follows:

JavaScript

It also worked when I had the function addPizza() inside the script at .blade.php.

Also, find the repository on GitHub if you need any further code reviews: https://github.com/andrelandgraf/laravel-docker

EDIT: When I copy the pizza.js inside <script><script> it works fine, but I receive a SyntaxError: import declarations may only appear at top level of a module. This SyntaxError dissapears when I import the script via src like you can see in my code examples. For me, this indicates that the script is not loaded at all.

EDIT2 & Solution: I used @kerbholz solution. I added @stack('scripts') to the bottom of the body in app.blade.php and inside @section('content') of index.blade.php I know @push('stack') the pizza.js file.

I am now one step further but I still receive the SyntaxError stated in EDIT. Is there a workaround for that or do I just have to remove the import of PizzaService.js and add a <scipt>-Tag for this file as well?

EDIT3: Okay this issue is not related. It looks like ES6 modules are not yet supported by browsers.

Advertisement

Answer

Anything outside of your @section block will not be rendered.

You could edit your layouts/app.blade.php and add a @stack('head') where you want your styles/javascript to appear (preferably in the <head> section of your HTML).

In any blade file that @extends('layouts.app') you can then use

JavaScript

to push content into that stack.

For more information visit https://laravel.com/docs/5.6/blade#stacks

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement