Pink Panther
Pink Panther

Reputation: 23

Laravel pass value to javascript

Im learning laravel. I wanna ask a stupid question. Hope be helped from all of you.

When a controller return a view, I can send value blade template.

return view('home', ['message' => 'this is home page']);

I can get that from home.blade.php as:

<h1>{{$message}}</h1>

I can even send that value to javascript by the way below:

var message = "{{$message}}";

Yeah, that it!

But how can i send that value to separate javascript file.

/resources/views/home.blade.html:

<script src="/js/home.js"></script>

how can i get that value to /public/js/home.js if i dont use the way below?

<script>var message = {{$message}}</script>
<script src="/js/home.js"></script>

Thank for reading!

Upvotes: 2

Views: 12625

Answers (1)

Belal mazlom
Belal mazlom

Reputation: 1850

You can make a script tag contain all your dynamic values, and make your file

/js/home.js

use it

like this

<script>
   var appSettings = {message :"{{$message}}"};
</script>
<script src="/js/home.js"></script>

so inside home.js you can access this value

alert(appSettings.message);

Upvotes: 10

Related Questions