Using Thymeleaf in Java Script code

Asked

Viewed 1,607 times

1

Good evening friends,

I had a javascript code extract using JSP tags that generated a pizza chart and works correctly. Now I need to migrate to Thymeleaf and I have no idea how to write the code. The javascript code with JSP is like this:

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

2 answers

2

Good afternoon, you can use Inline for Javascript, so you can access the view variables directly within the JS code. For example:

<script th:inline="javascript">
  /*<![CDATA[*/
  ...

  var titulo = [[${model.pessoa.nome}]];

  ...
  /*]]>*/
</script> 

I hope I’ve helped.

0

Good morning! I did something similar to pass a Base64 to the JS coming from a Hymeleaf. See:

<script th:inline="javascript">
/*<![CDATA[*/
  var livro_pdf = /*[[${livro.pdf_string}]]*/ "Livro";
/*]]>*/

window.downloadPDF = function downloadPDF() {

    var dlnk = document.getElementById('dwnldLnk');
    dlnk.href = pdf;

    dlnk.click();


    alert('Download Realizado com Sucesso!');
}
var b64 = document.getElementsByName('livro').value;
var pdf = 'data:application/octet-stream;base64,' + livro_pdf;

</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.