【问题标题】:Thymeleaf: combining literals with variablesThymeleaf:将文字与变量结合起来
【发布时间】:2018-09-30 21:56:47
【问题描述】:

我在 Thymeleaf 中有这段代码:

<tr th:each="image: ${images}" >
    <img th:onmouseover="'javascript:imageName(\'theImageName\' + ${image.id} +'\');'"> 
</tr>

但我遇到了解析错误

【问题讨论】:

    标签: javascript html spring-boot thymeleaf


    【解决方案1】:

    我有两个观察结果:

    打开标签?

    某些 Thymeleaf 模板模式要求模板格式正确。如果是这种情况,任何 unclosed img 标签都会导致解析错误。

    发生这种情况时,java 堆栈跟踪会提供信息:

    org.xml.sax.SAXParseException: The element type "img" must be terminated by the matching end-tag "</img>".
    

    但您可能在浏览器中看到的错误不是:

    Exception parsing document: template="home", line 19 - column 6
    

    我的最低配置 Spring Boot 应用程序默认为这些更严格的模式之一(HTML5?XML?),所以@Metroids' 和 @ErikMD 的答案都给了我一个解析错误,但如果我都可以工作关闭图片标签。

    如果您不是这种情况,使用 java 堆栈跟踪更新问题可能会有所帮助。

    管道

    我认为所有这些撇号和加号会使标记难以阅读(和书写)。使用literal substitutions with pipes 可以说更清晰(并且更不容易出错):

    <img th:onmouseover="|javascript:imageName('ImageName${image.id}');|" />
    

    甚至:

    <img th:onmouseover="|imageName('ImageName${image.id}')|" />
    

    如果您不喜欢这种方法,也可以通过删除theImageName之后的反斜杠来修复您问题中的代码:

    <img th:onmouseover="'javascript:imageName(\'theImageName' + ${image.id} +'\');'" />
    

    【讨论】:

      【解决方案2】:

      你可以试试下面的

      <img th:onmouseover="'javascript:imageName(\''+ theImageName\' + ${image.id} +'\');'"> 
      

      【讨论】:

      • @enLopes 您现在可以试试吗?我已经更新了我的答案
      • 同样的结果 :-(
      【解决方案3】:

      我会这样格式化:

      <tr th:each="image: ${images}" >
          <img th:onmouseover="${'javascript:imageName(''theImageName' + image.id + ''');'}"> 
      </tr>
      

      【讨论】:

      • @enLopes 我用变量测试了这个......如果你仍然遇到解析错误,那么还有其他事情发生。
      【解决方案4】:

      你可以试试下面的代码吗?

      <img th:attr="onmouseover=${'javascript:imageName(''theImageName' + image.id + ''');'}">
      

      这个答案的灵感来自that other SO answer,Thymeleaf 文档的相关部分是5.1: Setting the value of any attribute

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-24
        • 2017-12-02
        相关资源
        最近更新 更多