Laravel 5.2 Javascript call with blade parameter
Alright, so I found the solution.
I had to first do the parameter initialisation in PHP:
<?php $json = json_encode($module); ?>
And then separately call the Javascript function via:
@section('scripts')
<script type="text/javascript">
$(document).ready(function() {
var module = {!! $json !!};
createMixin(module);
});
</script>
@endsection
So in total it would look like this:
<?php $json = json_encode($module); ?>
@section('scripts')
<script type="text/javascript">
$(document).ready(function() {
var module = {!! $json !!};
createMixin(module);
});
</script>
@endsection
Mentenyia
Updated on June 14, 2022Comments
-
Mentenyia almost 2 years
I have (currently) the following bit of code in my module.blade.php:
@section('scripts') <script type="text/javascript"> createMixin(['{{ $module }}']); </script> @endsection
Explanation:
- $module is a variable holding a JSON packed with simple key => value, but also with key => object. It is loaded previously in a Controller and displayed in the blade.php.
Example:
{ "title":"Title", "name":"dummy", "file":"dummy", "layout":"normal", "fields": [ { "name": "bla" } ] }
- Function createMixin() would ideally generate a HTML out of Jade with the options inside $module (already existing).
Problem is: This does end in an error message: "htmlentities() expects parameter 1 to be string, array given"
Done so far: I have already tried several things:
@section('scripts') <script type="text/javascript"> var fields = $.parseJSON("{!! $module !!}"); createMixin(fields); </script> @endsection
And:
@section('scripts') <script type="text/javascript"> createMixin("{!! JSON.parse($module) !!}"); </script> @endsection
And:
@section('scripts') <script type="text/javascript"> createMixin("{!! json_encode($module) !!}"); </script> @endsection
And:
@section('scripts') <script type="text/javascript"> $(this).createMixin("{{ $module }}"); </script> @endsection
I have had a look at several posts here (like this one) and in other sources, they tell the people to use the php implode method or just a simple usage of "{!! !!}". But this all ends up in the same error message.
Question: What am I overlooking here? What am I doing wrong?
Edit:
As requested my Javascript function:
//generate one jade mixin function createMixin(module) { //first load JSON... var json = $.parseJSON(loadJSON(module["file"])); //get options for mixin var options = json.fields; //detect jade file var jadepath = RESOURCES_DIR + "views/jade/" + json.file + "/template.jade"; //check if file exists $.ajax({ 'url': jadepath, 'type': 'HEAD', 'error': function() {}, 'success': function () { var html = renderJade(options, jadepath); //save html into json json.html = html; var tmp = new Blob([html], { type: 'plain/text;charset=utf-8' }); } }); };