如何在javascript代码中使用thymeleaf?

时间:2017-07-30 23:31:54

标签: javascript jsp spring-mvc thymeleaf

我有一个带有javascript代码的JSP页面,我已经编写并运行良好。我需要使用百日咳重写相同的代码,但是不起作用。 JSP javascript代码:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});

  google.charts.setOnLoadCallback(drawChartPie);

  function drawChartPie() {

    var data = google.visualization.arrayToDataTable([
      ['Conta', 'Valor'],         
        <c:forEach items="${model.contaCorretora }" var="contaCorretora">
      ['${contaCorretora.tipoConta}', ${contaCorretora.valorAtual}],
    </c:forEach>
      ]);

    var options = {
      title: '${model.pessoa.nome }'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }

</script>

我没有找到将此代码迁移到百里香的方法。

更新1:

我按照你的建议使用了代码,但仍然无效:

<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':['corechart']});

  google.charts.setOnLoadCallback(drawChartPie);

  var array = [[${investimento}]];

  function drawChartPie() {

    var data = google.visualization.arrayToDataTable([
      ['Conta', 'Valor'],         
      for (i in array)
      {
        ['array[i].tipoConta', array[i].valorTotalDolar],    
      }
      ]);

    var options = {
      title: 'Teste'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }   

  /]]>*/
</script>

1 个答案:

答案 0 :(得分:0)

首先使用th:inline启用JavaScript内联:

<script type="text/javascript" th:inline="javascript">

然后使用双括号表达式插入对象:

var options = {
  title: [[${model.pessoa.nome}]];
};

而不是foreach,您应该使用Thymeleaf(在Jackson库的帮助下)将对象序列化为JSON的事实:

var contaCorretora = [[${model.contaCorretora}]];
// "contaCorretora" is now a JavaScript object,
// make an array out of it or what you want