Twig: JS escaping produces invalid JSON?

Created on 5 Nov 2016  Â·  5Comments  Â·  Source: twigphp/Twig

Hi everyone, I'm afraid I'm asking a stupid question but here it goes:

<script>
var foo = {
    "bar": "{{ 'Hello world'|e('js') }}"
};
</script>

This produces:

<script>
var foo = {
    "bar": "Hello\x20world"
};
</script>

This runs fine in JS but it seems to be considered invalid JSON (http://jsonlint.com/):

{
    "bar": "Hello\x20world"
}

(even GitHub shows it in red)

The actual issue for me is that Google doesn't accept that for structured data in HTML pages, but I can see plenty of issues with invalid JSON.

Am I mis-using the |e('js') filter? If so, what should I use instead? If not, is that a bug?

All 5 comments

Your issue is that JSON is just a subset of JavaScript. So you have no guarantee that a JavaScript string is valid JSON. Though it seems that you are actually looking for the json_encode filter.

you sure you don't want to try something like https://twigfiddle.com/q54hcm ?

oh @xabbuh was just about the same time :+1: :)

Thanks! json_encode is a solution but it's not intuitive (because it's different from other escaping methods). Would it make sense to add a new |e('json') context?

Not sure if that's really a common use case. How often do you really create JSON object structures from partial structures (i.e. building them inside a template)? I guess commonly you will just dump/encode a previously built object graph.

Not a JS expert here :) But closing as it seems @xabbuh gave the right answer.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xxfaxy picture xxfaxy  Â·  6Comments

su-narthur picture su-narthur  Â·  6Comments

mpdude picture mpdude  Â·  3Comments

Seldaek picture Seldaek  Â·  6Comments

koflerdavid picture koflerdavid  Â·  3Comments