javascript - 在 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>
解决方案
我建议使用#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
直接在src
URL 中使用该值来进一步简化此操作:
<script th:inline="javascript"
th:src="@{/resources/jquery/js/jquery.timeago.{lang}.js(lang=${#locale.language})}"
type="text/javascript"></script>
现在,不需要使用任何th:if
语句,您只需要一个<script>
标签,而不是一长串可能的标签。
推荐阅读
- java - OneToMany 关系中的 JPA 查询未按预期工作
- javascript - 使用 JavaScript 按下浏览器后退按钮时重定向到 URL
- debugging - 是否可以使用内置终端调试应用程序
- ubuntu - 如何修复 IntelliJ IDEA 安装错误?
- mysql - 在 Laravel/MySQL 中防止竞争条件插入
- python - Gif 到 base64 编码而不保存文件
- python - Google Automl 400 错误位置 ID 和字段:名称无效
- android - 尝试在某些设备上加载 LobbyScreen 时显示错误
- javascript - Chrome 83:无法上传文件
- google-drive-api - 谷歌选择器 + 谷歌云端硬盘 API