Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a random version number to javascript file in thymeleaf template

Tags:

java

thymeleaf

I have a main.js in thymeleaf template, each time I call it I want to add a version parameter so that it will not be cached and my latest changes will work.

    <script src="/main.js?version=345345456"></script>
</body>
</html>

Since it's the layout behind all other templates, I don't want to pass a variable from controllers.

So I decided to add a bean method to my application class

@SpringBootApplication
public class NexusApplication {

    @Bean
    public double jsVersion(){
        return Math.random();
    }

}

Than I added:

<script th:src="@{/js/my-script.js(version=NexusApplication.jsVersion())}"></script>

Output is:

<script th:src="@{/main.js?(version=NexusApplication.jsVersion())}"></script>

What am I missing? How should I approach this issue in a better way?

like image 202
tolga Avatar asked Nov 14 '25 21:11

tolga


1 Answers

One Java approach is to generate a random value using your method if you want, or see How do I generate random integers within a specific range in Java?, if you want an integer with a certain number of digits in it.

Then you can add that value (let's call it randNumber) to the template's model in the usual Spring way - for example:

model.addAttribute("randNumber", randNumber);

Now you can use the following in your Thymeleaf template:

<script th:src="@{/main.js(version=${randNumber})}"></script>

Note how the variable needs to be a Thymeleaf expression in ${...}.


One alternative approach, which may be acceptable is to use Thymeleaf's expression utility method for random alphanumeric strings:

${#strings.randomAlphanumeric(count)}

So, for example, for a string of length 5:

<script th:src="@{/main.js(version=${#strings.randomAlphanumeric(5)})}"></script>

You don't need any Java for this.

The end result would be similar to the first approach, but can contain characters as well as digits:

<script src="/main.js?version=2Q931"></script>
like image 149
andrewJames Avatar answered Nov 17 '25 11:11

andrewJames



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!