Store PHP variable with HTML in JavaScript in Laravel Blade Template

javascript, jquery, laravel, php

Solution

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, '"') !!}";

Problem

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?

Original source

Related problems