Search code examples
javascripthtmlthymeleaf

how to include an element ONLY when it's not rendered with Thymeleaf?


Our Angular application can be served both via Spring Boot and via "ng serve" (mostly for development purposes). In the first case, it's index.html is rendered with Thymeleaf, in the latter it's not.

And I need to include a <script>, which will have src as url A in the first case (a prod script, when served via Thymeleaf) and url B (dev link) in the second case..

Can't think of way to do it. I can do

<script th:src='url-A'></script>
<script src='url-B'></script>

which is OK for the 'dev' deployment (no Thymeleaf), but when it's served with Thymeleaf, both elements will be rendered and thus processed by browser, which I would want to avoid..

I wonder if there's any construction that would let me have something in the template, that is a safe and valid HTML when it's not processed by Thymeleaf; AND is rendered to nil (empty string) when it is ?


Solution

  • There are a couple easy ways to accomplish this. The easiest is simply including a th:src and a src. Thymeleaf will overwrite the static src when it's rendered in SpringBoot (and it will be left alone when served via ng serv).

    <script src="url-B" th:src="url-A"></script>
    

    You can also use the th:remove attribute.

    <script th:src="url-A"></script>
    <script src="url-B" th:remove="all"></script>