Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store PHP variable with HTML in JavaScript in Laravel Blade Template

I need a way to store HTML from a PHP variable in JavaScript.

var contents = "{{ $template }}";

This generates an error however. I guess it's because it's not escaped properly, So it messes up the web browser, because JS cannot store it properly... I've tried Laravel escaping

var contents = "{{ e($template) }}";

without any success.

The end goal is: $('#preview-iframe').contents().find('html').html(contents);

How can I accomplish this?

like image 222
John Avatar asked Jun 03 '14 09:06

John


2 Answers

The double curly brackets {{ }} will always convert special characters to HTML entities. Try using {!! !!} to render the code exactly. However, you will want to make sure you escape the double quotes in the string.

So this:

var contents = "{{ $template }}";

Should be something like:

var contents = "{!! addcslashes($template, '"') !!}";
like image 110
jon__o Avatar answered Sep 21 '22 17:09

jon__o


I used this workaround for the same problem

var contents = atob("{{ base64_encode($contents) }}");

This is very convenient, because you don't have to escape any characters, and you are guaranteed that there won't be any syntax errors with javascript.

One downside is that atob() function is supported in IE10 and up - Source

like image 38
Mirza Brunjadze Avatar answered Sep 22 '22 17:09

Mirza Brunjadze