Passing a PHP Variable to JavaScript in a Blade Template

Using JavaScript to display Laravel's Variable

For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:

var jobs = JSON.parse("{{ json_encode($jobs) }}");

Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready is the answer to that)

<script>
var jobs = JSON.parse("{{ json_encode($jobs) }}");
</script>

If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.

How to set up Javascript AS a Blade template for use in an API endpoint?

I solved this by adding just a couple of simple steps to accommodate my needs.

To clarify, this controller routes an api endpoint that is pulled into an external site as script like this:

<script defer>
js = document.createElement('script');
js.setAttribute('src', 'https://example.com/api/v1/get_js');
js.setAttribute('type', 'text/javascript');
document.head.appendChild(js);
</script>

So it has to pull javascript without the tags. However, editing the blade within my IDE doesn't like it because it's a blade.php file, and I want the automatic code styling for JS.

Therefore, I updated the controller to add a variable $included:

class JSPluginController extends Controller
{
public function index()
{
$included = true;
$env = \App::environment();

return view('js/main', compact('included', 'env'));
}
}

The $included variable then gets passed into the blade (/resources/views/js/main.blade.php), and this still allows my IDE to do its code formatting:

@if(!$included)
<script>
@endif
let hello_world = "{{ $env }}";
document.write("The environment is: " + hello_world);
@if(!$included)
</script>
@endif

This satisfies my needs beautifully! I can use all the power and control of blade, and still retain my code formatting. Happy coding.



Related Topics



Leave a reply



Submit