From 612fa7bc514ab88110c974ba5a330ef2ec2c2363 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 24 Jun 2011 11:26:17 +0200 Subject: [PATCH] fixed json_encode filter (thanks to Koc for the fix) --- lib/Twig/Extension/Core.php | 20 +++++++++++++++++++- test/Twig/Tests/Fixtures/filters/json_encode.test | 12 ++++++++++++ 2 files changed, 31 insertions(+), 1 deletions(-) create mode 100644 test/Twig/Tests/Fixtures/filters/json_encode.test diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index b65f732..a1cdf42 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -48,7 +48,7 @@ class Twig_Extension_Core extends Twig_Extension // encoding 'url_encode' => new Twig_Filter_Function('twig_urlencode_filter'), - 'json_encode' => new Twig_Filter_Function('json_encode'), + 'json_encode' => new Twig_Filter_Function('twig_jsonencode_filter'), // string filters 'title' => new Twig_Filter_Function('twig_title_string_filter', array('needs_environment' => true)), @@ -232,6 +232,24 @@ function twig_urlencode_filter($url, $raw = false) return urlencode($url); } +function twig_jsonencode_filter($value, $options = 0) +{ + if ($value instanceof Twig_Markup) { + $value = (string) $value; + } elseif (is_array($value)) { + array_walk_recursive($value, '_twig_markup2string'); + } + + return json_encode($value, $options); +} + +function _twig_markup2string(&$value) +{ + if ($value instanceof Twig_Markup) { + $value = (string) $value; + } +} + function twig_array_merge($arr1, $arr2) { if (!is_array($arr1) || !is_array($arr2)) { diff --git a/test/Twig/Tests/Fixtures/filters/json_encode.test b/test/Twig/Tests/Fixtures/filters/json_encode.test new file mode 100644 index 0000000..776a631 --- /dev/null +++ b/test/Twig/Tests/Fixtures/filters/json_encode.test @@ -0,0 +1,12 @@ +--TEST-- +"json_encode" filter +--TEMPLATE-- +{{ "foo"|json_encode|raw }} +{{ foo|json_encode|raw }} +{{ [foo, "foo"]|json_encode|raw }} +--DATA-- +return array('foo' => new Twig_Markup('foo')) +--EXPECT-- +"foo" +"foo" +["foo","foo"] -- 1.7.2.5