首页 > 解决方案 > 在 Thymeleaf 中动态添加 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>

标签: javascriptspringspring-bootthymeleaf

解决方案


我建议使用#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>

但是您可以通过#locale.language直接在srcURL 中使用该值来进一步简化此操作:

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

现在,不需要使用任何th:if语句,您只需要一个<script>标签,而不是一长串可能的标签。


推荐阅读