在Thymelaf中动态添加JavaScript资源



我有timeago.js插件,它需要一些用于区域设置的文件。但你不可能一次加所有的。它应该是相对当前的区域设置。所以我需要一些类似switch或if条件的东西来添加资源。我试过了,但不起作用。

<script th:if="${#locale == 'az_AZ'}" th:src="@{/resources/jquery/js/jquery.timeago.az.js}" type="text/javascript"></script>
<script th:if="${#locale == 'ru_RU'}" th:src="@{/resources/jquery/js/jquery.timeago.ru.js}" type="text/javascript"></script>

我建议使用#locale.language只获取上下文区域设置的语言部分,尤其是因为这是JS文件名需要匹配的部分。

所以,像这样的东西:

<script th:inline="javascript" 
th:if="${#locale.language == 'en'}"  
th:src="@{/resources/jquery/js/jquery.timeago.en.js}" 
type="text/javascript"></script>
<script th:inline="javascript" 
th:if="${#locale.language == 'ru'}"  
th:src="@{/resources/jquery/js/jquery.timeago.ru.js}" 
type="text/javascript"></script>

但是,您可以更进一步,通过直接在srcURL:中使用#locale.language值来简化这一过程

<script th:inline="javascript" 
th:src="@{/resources/jquery/js/jquery.timeago.{lang}.js(lang=${#locale.language})}" 
type="text/javascript"></script>

现在,不需要使用任何th:if语句,只需要一个<script>标记,而不需要它们的长列表。

最新更新