Which filter do I need to json_encode
a string with special characters and spaces? Is there maybe any better approach to pass a json
object with the translated strings from twig
variables to a template in Vue.js
?
I tried this;
{# renders: äeiöü #}
<p>{{'string1'|trans}}</p>
{# renders: this is a string with spaces #}
<p>{{'string2'|trans}}</p>
{% set snippets = {
string1: 'string1'|trans,
string2: 'string2'|trans,
} %}
<div id="app" snippet={{ snippets|json_encode }}>
<demo></demo>
</div>
<script>
let snippetJSON = document.getElementById('app').getAttribute('snippet');
//Output: {"string1":"\u00e4ei\u00f6\u00fc","string2":"this
console.log(snippetJSON);
</script>
CodePudding user response:
Thanks to @deceze in the comments. The attribute had to be in quotes. Also @WPhil is right, the JSON.parse() part was also missing.
CodePudding user response:
You need to use JSON.parse()
to decode the orignial values.