我可以看到有两种方法可以实现这一点 - 但它们都对您问题的更广泛背景做出了一些假设。如果这些假设是错误的,那么这些方法可能不起作用。
选项 1 的 2
将 Thymeleaf 提供的参数从 Thymeleaf 模板传递给您的函数(位于单独的 JS 文件中)。
这简化了解决方案。假设(与您的问题不同)是您仅在 Thymeleaf 模板中调用此函数 - 因此您不需要将消息字符串直接呈现到 JS 代码中(在其单独的 JS 文件中)。
例子:
我使用以下消息文件 - jsdemo.properties:
demo.error1=Error message one
demo.error2=Error message two
这是我示例中的 JS 文件 - js_demo.js:
function getErrorMessagesA(msg1, msg2) {
console.log('parameter A1 = ' + msg1);
console.log('parameter A2 = ' + msg2);
}
这是调用getErrorMessagesA的Thymeleaf模板:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>JS Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="js/js_demo.js"></script>
</head>
<body>
<h2 id="derf">JS Demo</h2>
</body>
<!-- option 1: call the function in an external script with parameters: -->
<script th:inline="javascript">
$(document).ready(function() {
getErrorMessagesA( [[#{welcome.error1}]], [[#{welcome.error2}]] );
});
</script>
</html>
Thymeleaf 模板使用 [[#{...}]] 语法将 Thymeleaf 变量嵌入 JavaScript。见expression inlining。
网页渲染时,控制台显示两条消息如下:
parameter A1 = Error message one
parameter A2 = Error message two
选项 2 的 2
这使用了一种不同的方法,其中 JS 作为片段添加到 HTML 模板中(意味着它可以在不同的模板中重复使用。在这种情况下,该函数被调用时不带参数。
片段使用这个嵌入到主模板中(它替换了上面代码中的“选项1”部分):
<!-- option 2: process the function as a Thymeleaf fragment: -->
<th:block th:replace="jsdemo_jscode.html :: js_fragment_1" ></th:block>
<script th:inline="javascript">
$(document).ready(function() {
getErrorMessagesB();
});
</script>
Thymeleaf 片段文件:
<th:block th:fragment="js_fragment_1">
<script th:inline="javascript">
function getErrorMessagesB() {
console.log('parameter B1 = ' + /*[[#{demo.error1}]]*/ '[msg not found]');
console.log('parameter B2 = ' + /*[[#{demo.error2}]]*/ '[msg not found]');
}
</script>
</th:block>
这使用 Thymeleaf 的 natural templating 语法:/*[[#{demo.error1}]]*/,以确保 JavaScript 有效。还要注意th:inline="javascript" 指令。
网页渲染时,控制台显示两条消息如下:
parameter B1 = Error message one
parameter B2 = Error message two
这里的主要区别是片段中对 JS 的调用没有参数 - 它只是 getErrorMessagesB();。
选项 3 的 2
理论上还有第三种选择——但我从来没有这样做过。我认为这会很复杂。
您可以在您的 Thymeleaf 模板 getErrorMessagesB(); 中使用无参数调用 - 但不是使用选项 2 中的 JS 片段,而是使用选项 1 中的外部 JS 文件。
这里的JS如下:
function getErrorMessagesB() {
console.log('parameter B1 = ' + /*[[#{demo.error1}]]*/ '[msg not found]');
console.log('parameter B2 = ' + /*[[#{demo.error2}]]*/ '[msg not found]');
}
这样做的复杂性在于,除了 HTML 文件之外,您还需要 process this file(但与 HTML 文件分开),并使其可用于 HTML 文件。我使用过文本模板,但从来没有依赖于相关的 HTML 模板。