Skip to content

Commit d42a080

Browse files
committed
Add Twig Extension to get some datatable config as json string.
1 parent 58900d1 commit d42a080

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{% spaceless %}
2+
{
3+
"selector": "#sg-datatables-{{ sg_datatables_view.uniqueName }}",
4+
{% include '@SgDatatables/datatable/language.html.twig' %},
5+
{% include '@SgDatatables/datatable/ajax.html.twig' %}
6+
{% include '@SgDatatables/datatable/options.html.twig' %}
7+
{% include '@SgDatatables/datatable/features.html.twig' %}
8+
{% include '@SgDatatables/datatable/callbacks.html.twig' %}
9+
{% include '@SgDatatables/datatable/extensions.html.twig' %}
10+
{% include '@SgDatatables/datatable/columns.html.twig' %},
11+
{% include '@SgDatatables/datatable/initial_search.html.twig' %}
12+
}
13+
{% endspaceless %}

Twig/DatatableTwigExtension.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,11 @@ public function getFunctions()
7070
[$this, 'datatablesRenderJs'],
7171
['is_safe' => ['html'], 'needs_environment' => true]
7272
),
73+
new TwigFunction(
74+
'sg_datatables_render_json',
75+
[$this, 'datatablesRenderJson'],
76+
['is_safe' => ['html'], 'needs_environment' => true]
77+
),
7378
new TwigFunction(
7479
'sg_datatables_render_filter',
7580
[$this, 'datatablesRenderFilter'],
@@ -142,6 +147,27 @@ public function datatablesRenderJs(Environment $twig, DatatableInterface $datata
142147
);
143148
}
144149

150+
/**
151+
* Renders the json config options.
152+
*
153+
* @return string
154+
*/
155+
public function datatablesRenderJson(Environment $twig, DatatableInterface $datatable)
156+
{
157+
$json = $twig->render(
158+
'@SgDatatables/datatable/datatable_js.json.twig',
159+
[
160+
'sg_datatables_view' => $datatable,
161+
]
162+
);
163+
164+
// Try to make valid json string, remove comma before [ { etc.
165+
$regex = '/\,(?!\s*?[\{\[\"\'\w])/';
166+
$json = preg_replace($regex, '', $json);
167+
168+
return $json;
169+
}
170+
145171
/**
146172
* Renders a Filter template.
147173
*

0 commit comments

Comments
 (0)