简体   繁体   English

使用 Thymeleaf 从 Spring model 设置一个 JavaScript 变量

[英]Setting up a JavaScript variable from Spring model by using Thymeleaf

I am using Thymeleaf as template engine.我使用 Thymeleaf 作为模板引擎。 How I pass a variable from Spring model to JavaScript variable?我如何将变量从 Spring model 传递到 JavaScript 变量?

Spring-side:弹簧侧:

@RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
    model.addAttribute("message", "hello");
    return "index";
}

Client-side:客户端:

<script>
    ....
    var m = ${message}; // not working
    alert(m);
    ...
</script>

According to the official documentation :根据官方文档

<script th:inline="javascript">
/*<![CDATA[*/

    var message = /*[[${message}]]*/ 'default';
    console.log(message);

/*]]>*/
</script>

Thymeleaf 3 now:现在百里香3:

  • Display a constant:显示一个常量:

    \n<script th:inline="javascript"> <script th:inline="javascript">\nvar MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ ""; var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";\n</script> </脚本>\n
  • Display a variable:显示一个变量:

    \nvar message = [[${message}]]; var message = [[${message}]];\n
  • Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).或者在以静态方式打开模板文件时(不在服务器上执行它)时在注释中获得有效的 JavaScript 代码。

    Thymeleaf calls this: JavaScript natural templates Thymeleaf 称之为:JavaScript 自然模板

    \nvar message = /*[[${message}]]*/ ""; var message = /*[[${message}]]*/ "";\n

    Thymeleaf will ignore everything we have written after the comment and before the semicolon. Thymeleaf 将忽略我们在评论之后和分号之前写的所有内容。

More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining更多信息: http : //www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining

var message =/*[[${message}]]*/ 'defaultanyvalue';

According to the documentation there are several ways to do the inlining.根据文档,有几种方法可以进行内联。
The right way you must choose based on the situation.您必须根据情况选择正确的方法。

1) Simply put the variable from server to javascript : 1) 只需将变量从服务器放到 javascript 中:

<script th:inline="javascript">
/*<![CDATA[*/

var message = [[${message}]];
alert(message);

/*]]>*/
</script>

2) Combine javascript variables with server side variables, eg you need to create link for requesting inside the javascript: 2)将javascript变量与服务器端变量结合起来,例如您需要创建用于在javascript内部请求的链接:

<script th:inline="javascript">
        /*<![CDATA[*/
        function sampleGetByJquery(v) {
            /*[+
            var url = [[@{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]] 
                      + "&var2="+v;
             +]*/
            $("#myPanel").load(url, function() {});
        }
        /*]]>*/
        </script>

The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).我无法解决的一种情况- 然后我需要在模板内部调用的 Java 方法中传递 javascript 变量(我猜这是不可能的)。

MAKE sure you have thymleaf on page already确保你已经在页面上有 thymleaf

//Use this in java
@Controller
@RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
 model.addAttribute("showTextFromJavaController","dummy text");
 return "showingTymleafTextInJavaScript";
}


//thymleaf page  javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>

我在野外看到过这种事情:

<input type="button"  th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />

If you use Thymeleaf 3:如果您使用 Thymeleaf 3:

<script th:inline="javascript">
    var username = [[${session.user.name}]];
</script>

Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html另一种方法是创建一个由 java 控制器返回的动态 javascript,就像在 thymeleaf 论坛中写的一样: http : //forum.thymeleaf.org/Can-I-use-th-inline-for-a-单独的javascript-file-td4025766.html

One way to handle this is to create a dynamic javascript file with the URLs embedded in it.处理此问题的一种方法是创建一个动态 javascript 文件,其中嵌入了 URL。 Here are the steps (if you are using Spring MVC)以下是步骤(如果您使用的是 Spring MVC)

@RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public String dynamicJS(HttpServletRequest request) {

        return "Your javascript code....";

}


  

Assuming request attribute named "message":假设名为“消息”的请求属性:

request.setAttribute("message", "this is my message");

To read it in the html page using Thymeleaf template:要使用 Thymeleaf 模板在 html 页面中阅读它:

<script>
  var message = "[[${message}]]";
  alert(message);
</script>

If you need to display your variable unescaped, use this format:如果您需要显示未转义的变量,请使用以下格式:

<script th:inline="javascript">
/*<![CDATA[*/

    var message = /*[(${message})]*/ 'default';

/*]]>*/
</script>

Note the [( brackets which wrap the variable.注意包裹变量的[(括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过Thymeleaf将Spring模型中的字符串值正确转换为JavaScript的字符串变量? - How to convert string value from Spring model to JavaScript's string variable via Thymeleaf correctly? 使用javascript innerHtml中的thymeleaf将数据传递到Spring Boot控制器 - Pass data to spring boot controller using thymeleaf from javascript innerHtml 从JavaScript访问Spring Model变量 - Get access to Spring Model variable from JavaScript 使用百里香在外部javascript中添加模型对象 - Adding model object in external javascript using thymeleaf 使用window.opener或其他方法将javascript变量值从弹出窗口设置为父窗口 - Setting javascript variable value from Pop-Up window to the parent using window.opener or something else 使用Thymeleaf传入的JavaScript变量的调用方法 - Calling method on JavaScript variable passed in using Thymeleaf 分配列表 <T> 使用thymeleaf在javascript中的变量 - Assign a list<T> to a variable in javascript using thymeleaf 使用th:inline设置百里香变量总是将变量设置为null - Setting thymeleaf variable using th:inline always sets the variable to null 将变量从 thymeleaf 传递给 javascript 函数? - Pass a variable from thymeleaf to a javascript function? 从包含瑞典语字符的模型字符串中设置javascript变量 - Setting javascript variable from model strings containing Swedish Characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM