How to write a filter for json_encode?

szisti
Member | 4
+
0
-

Hi, I'm trying to write a json_encode filter, but no matter what I do, it's printed escaped.
What I'm trying to achieve, is if I use the json_encode filter, then I get back a json object, but what I get instead, is an escaped string.

David Grudl
Nette Core | 7780
+
0
-

What do you mean by filter for json_encode?

szisti
Member | 4
+
0
-

I meant that I want to be able to use latte inside a script tag like this: var jsonObject = {$object|json_encode}
The only way I can make this work, is by writing it like this: var jsonObject = {$object|json_encode|noescape}

Here's a stackoverflow link: https://stackoverflow.com/…php-latte-v3

szisti
Member | 4
+
0
-

The only way to make this work by default is by using the function {json_encode($object)|noescape}, but I wanted to create a filter, so I can drop the noescape part…

Jan Tvrdík
Nette guru | 2595
+
+2
-

Because Latte understands HTML contexts and knows you are in JavaScript context, it will apply json_encode automatically, so it's enought to write

<script>
  var jsonObject = {$object}
</script>

See Context-Aware Escaping and Printing in JavaScript chapters in documentation.

szisti
Member | 4
+
0
-

Oh, I knew about the strings, but didn't realize it works for objects as well. That's pretty cool. Thanks!