Reputation: 3
I am attempting to dynamically create Javascript within a Thymeleaf template in order to use Google Chart's Timeline package (note - this package isn't available in the Spring version of Google's library).
I have a Thymeleaf fragment ganttchartvalue.html with the following code, which is then included into the actual page:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Card' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([ /*[[${Parms}]]*/ ]);
chart.draw(dataTable);
}
/*]]>*/
</script>
In my GanttController class, I have the following code:
String Parms = "[ 'MegaCorp App 1', new Date(2018, 7, 2), new Date(2019, 4, 9) ]"; model.put("Parms", Parms);
(model is of type Map).
This is close to working, but the output that is generated (final page source) is:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Card' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([ "[ 'MegaCorp App 1', new Date(2018, 7, 2), new Date(2019, 4, 9) ]"]);
chart.draw(dataTable);
}
/*]]>*/
</script>
Question:
How do I eliminate the additional double quotes (") before and after the inserted text in the dataTable.addRows method call so that this code works correctly?
Thanks
Upvotes: 0
Views: 1727
Reputation: 20487
Thymeleaf isn't designed to be used that way. You shouldn't be adding a JSON string to your model. What you should be doing instead is adding java objects that will output the same way. In your case:
model.put("parms", new Object[] {new String[] {"MegaCorp App 1", "2018-07-02", "2018-04-09"}});
And then in your javascript:
<script type="text/javascript" th:inline="javascript">
.
.
.
var rows = /*[[${parms}]]*/ null;
rows[0][1] = new Date(rows[0][1]);
rows[0][2] = new Date(rows[0][2]);
dataTable.addRows(rows);
.
.
.
</script>
Upvotes: 1