2

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!

2
  • You can do that easily using the querySelector Commented Apr 8, 2017 at 11:07
  • Why don't you pass an encoded value to your blade file and get that within a variable and access it as an object Commented Apr 8, 2017 at 12:13

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I thought about that, but i wanna send many values, i think it make javascript code in blade file be long. So i hope a another way :D
You can check these solutions: stackoverflow.com/a/2190927/292927

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.