首页 > 解决方案 > Inserting Javascript Fragment Using Thymeleaf Includes Double Quotes

问题描述

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

标签: springgoogle-visualizationthymeleaf

解决方案


Thymeleaf 不是为这种方式设计的。您不应该在模型中添加 JSON 字符串。相反,您应该做的是添加将以相同方式输出的 java 对象。在你的情况下:

model.put("parms", new Object[] {new String[] {"MegaCorp App 1", "2018-07-02", "2018-04-09"}});

然后在你的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>

推荐阅读