You can use {!! $lacation->name !!} but only if you know you can trust the data retrieved.
Mar 2, 2022
10
Level 2
Escaping JSON data in Blade
I have this blade snippet that generates some data for chart.js:
labels: [
@foreach ($locations as $location)
"{{ $location->name }}",
@endforeach
],
The problem is that if the name property contains HTML special chars, they are HTML escaped, so for example & is turned into &. This is as expected, however, the value is displayed as-is by chart.js and the encoded entities are visible.
I can make it work by disabling escaping, but that opens up the opportunity for XSS through the name property. I've tried various combinations of htmlentities and json_encode, but they all run into one problem or another.
How should I apply escaping that's appropriate for a JS context?
Level 2
I've made a very ugly workaround, but it works:
{!! str_replace('&', '&', htmlspecialchars($location->name)) !!}
I'd still like to hear if anyone has a better idea!
Please or to participate in this conversation.