let me down slowly
let me down slowly

Reputation: 1017

How to access static resources from thymeleaf javascript inline

I have a spring boot project where I need to access a .png image file located in my static/images directory from a javascript code. I am using thymeleaf. I am using th:inline="javascript" from an html file like this:

<script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/
    ...
       src: "<location of the image file>"
    ...
    /*]]>*/
    </script>

The png file is in src/main/resources/static/images directory and the javascript program is in an html file in src/main/resources/templates directory. I know I can use it using absolute path, but it will be not same when this will go in production, so I have to change it again. Thymeleaf has th:src to load static file from a context-based path, but it works only from html tags, is there anything similar for javascript?

Upvotes: 0

Views: 569

Answers (1)

Metroids
Metroids

Reputation: 20487

You can use the same standard URL syntax in inlined expressions as you do in regular Thymeleaf expressions.

<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
let src = /*[[@{/path/to/image.png}]]*/ null;
/*]]>*/
</script>

Upvotes: 2

Related Questions