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?
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, '"') !!}";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With