📅  最后修改于: 2023-12-03 14:48:03.625000             🧑  作者: Mango
jsoncencode
- PHPTwig is a popular template engine for PHP, used widely in web development. One of its built-in filters is jsoncencode
, which allows you to convert a Twig array or object to a JSON string.
{# array to JSON string #}
{{ myArray|jsoncencode }}
{# object to JSON string #}
{{ myObject|jsoncencode }}
The jsoncencode
filter takes no parameters.
In this example, we have an array of data that we want to convert to JSON and use in JavaScript.
{% set data = {
"name": "John Doe",
"age": 25,
"email": "johndoe@example.com"
} %}
<script>
var jsonData = {{ data|jsoncencode }};
console.log(jsonData);
</script>
The output will be:
{
"name": "John Doe",
"age": 25,
"email": "johndoe@example.com"
}
"
) around each key and value, as per the standard JSON format.jsoncencode
filter uses the json_encode
function internally, with the JSON_UNESCAPED_UNICODE
flag to preserve Unicode characters.jsoncencode
filter can also handle complex objects, including nested arrays and objects.