From ce6bd7ac602a1e1d3c441984bc42147435ba10d4 Mon Sep 17 00:00:00 2001 From: Cosmin-Romeo TANASE Date: Mon, 12 Mar 2018 14:57:09 +0000 Subject: [PATCH] Allow rendering templates inside button.buttonOptions - This is useful if you want to use a function to render the body of an export (for example). To use it, you just call the template as before. Will provide examples --- Resources/views/datatable/button.html.twig | 2 +- Twig/DatatableTwigExtension.php | 23 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Resources/views/datatable/button.html.twig b/Resources/views/datatable/button.html.twig index 6540db71..828f9a68 100644 --- a/Resources/views/datatable/button.html.twig +++ b/Resources/views/datatable/button.html.twig @@ -57,7 +57,7 @@ {% endif %} {% if button.buttonOptions is defined and button.buttonOptions is not same as(null) %} {% for key, option in button.buttonOptions %} - {{ key }}: {{ option|json_encode|raw }}, + {{ key }}: {{ option|sg_datatables_option_encode|raw }}, {% endfor %} {% endif %} }, diff --git a/Twig/DatatableTwigExtension.php b/Twig/DatatableTwigExtension.php index 65696374..7bcbf00f 100644 --- a/Twig/DatatableTwigExtension.php +++ b/Twig/DatatableTwigExtension.php @@ -103,6 +103,7 @@ public function getFilters() { return array( new Twig_SimpleFilter('sg_datatables_bool_var', array($this, 'boolVar')), + new Twig_SimpleFilter('sg_datatables_option_encode', array($this, 'optionEncode'), ['needs_environment' => true]), ); } @@ -278,4 +279,26 @@ public function boolVar($value) return 'false'; } } + + + /** + * Renders: A json encode, except a template for the body. Useful for export pdf + * + * @param mixed $value + * + * @return string + */ + public function optionEncode(Twig_Environment $twig, $value) + { + $value = json_encode($value); + + preg_match('@\{\"template\"\:\".*?\"\}@si', $value, $matches); + + foreach ($matches as $match){ + $template = json_decode($match, true)["template"]; + $value = str_replace($match, $twig->render($template), $value); + } + + return $value; + } }