Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf conditional JavaScript function call

Tags:

thymeleaf

I'm developing a Spring Boot web application with Thymeleaf as the template engine.

I want to call a JavaScript function as soon as the page loads, if a specific attribute is present in the Model.

I did some research and I found a way to call a function but with clicking on a span etc., which doesn't do the job for me.

Thanks in advance.

like image 314
fspasovski Avatar asked Sep 16 '25 23:09

fspasovski


1 Answers

You basically want to call a Javascript method depending on a Thymleaf variable as soon as the page loads.

Try this

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

    var flag = [[${flag}]]; //Your Thymleaf variable
    window.onload = function() {
        if(!flag)
            return; // Exit/Return if the variable is false
        spreadLove(); // Call your favourite method if the variable is true
    };

/*]]>*/
</script>
like image 111
Abdullah Khan Avatar answered Sep 19 '25 15:09

Abdullah Khan