Accesing external Javascript (Chart.js) with Thymeleaf

👍:-1

I kind of have an answer. In this youtube video
https://www.youtube.com/watch?v=AEy7Hlz58bw? it is explained how to “externalize” JavaScript files. However, it is not really intuitive.

Javascript had to be written without function() part (which is something that i dont really understand)

//function done(xAxisData, yAxisData) {
    var ctx = document.getElementById("ChartDemo").getContext('2d');
    var ChartDemo = new Chart(ctx, {
        type : 'line',
        data : {

            labels : xAxisData,
            datasets : [ {
                label : "Chart-1",
                borderColor : 'rgb(10, 0, 0)',
                lineTension : 0,
                fill : false,
                data : yAxisData,
            }, ]
        },
        options : {
            responsive : true,
        }
    });
//}

and respective HTML needs to look like this

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link href="../static/css/Layout.css" th:href="@{/css/test.css}"
    rel="stylesheet" />
<link href="../static/js/drawChart.js" th:href="@{/js/drawChart.js}"
    rel="javascript" />

</head>
<body>
    <h2>Donkey</h2>
    <p>punch</p>
    <canvas id="ChartDemo"></canvas>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
    <script type="text/javascript" th:inline="javascript">
        /*<![CDATA[*/
        var xAxisData = /*[[ ${label} ]]*/[];
        var yAxisData = /*[[ ${point} ]]*/[];
        /*]]>*/
    </script>
    <script src="/js/drawChart.js"></script>
</body>
</html>

basically part where attributes xAxisData and yAxisData are initialized, could not contain the external script file.
If i manage to find more suitable solution, i will be glad to post it as an update to this answer as i have noticed that a lot of people get stuck in similar problems

BR DK

Leave a comment