phptemplatinglatte

How to write an unescaped javascript filter in php-latte v3


I'm basically trying to write a json_encode filter, by which I'm hoping to get a raw json object, but what I'm getting instead, is an escaped string of the json object.

Expected result:

{"foo":"bar"}

Actual result:

"{\"foo\":\"bar\"}"

Right now the only way I can get it the way I want, is by using the noescape filter, but this makes it unnecessarily more ugly

{$object|json_encode|noescape}

My json_encode filter

public static function json_encode(FilterInfo $info, mixed $value): string {
    $info->contentType = ContentType::JavaScript;
    return json_encode($value);
}

Solution

  • Found the answer in their forum.

    This isn't very obvious from the documentation, but seems like since latte understands the context automatically, you don't really need any filter for json_encode, just need to write it as: var jsonObject = {$object} and it will automatically encode it to json