Reputation: 9373
In a Laravel 5 blade template I have a <script>
section.
In this section I need to set a variable to a string that is coming from another blade template.
I tried something like :
<script>
var a = "@include 'sometext.blade.php' ";
</script>
but this obviously doesn't work.
Also, the included blade can contain both single and double quotes, so these need to be escaped somehow, or the Javascript will not be valid.
Any ideas?
Upvotes: 5
Views: 4781
Reputation: 426
Ended up needing similar functionality when working with DataTables, and the additional actions HTML needs to be injected after the fact via jQuery.
First I created a helper function with this (from Pass a PHP string to a JavaScript variable (and escape newlines)):
function includeAsJsString($template)
{
$string = view($template);
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
Then in your template you could do something like:
$('div.datatable-toolbar').html("{!! includeAsJsString('sometext') !!}");
to include the sometext.blade.php
blade template with escaping of quotes and removal of newlines.
Upvotes: 7