简体   繁体   中英

How to use thymeleaf inside of javascript code?

I have a JSP page with a javascript code that I've written and works well. I need to re-write the same code using thymeleaf, but isn't working. The JSP javascript code:

<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>

I didn't find the way to migrate this code to thymeleaf.

UPDATE 1:

I've used the code as you suggest me, but still doesn't work:

<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>

First enable JavaScript inlining with th:inline :

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

Then use double-bracket expression to insert an object:

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

Instead of foreach , you should use the fact that Thymeleaf (with help with from Jackson library) can serialize an object to JSON:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM