How to call object's method from Thymeleaf?

后端 未结 3 1740
无人及你
无人及你 2020-12-16 21:56

My template do not see objects, passed from Spring.

My code:

public class PublicModelAndView extends ModelAndView {

    @Autowired
    TemplateModul         


        
相关标签:
3条回答
  • 2020-12-16 22:17

    That can be done in Thymeleaf in two ways:

    First is to use special for Thymeleaf:

    <head th:fragment="publicSiteHeader">
    
        <title>SOME TITLE</title>
    
         <th:block th:text="${CSSProcessor.setDebugCaller("Public")}"/>
         <th:block th:text="${CSSProcessor.setSiteRegion("public")}"/>
         <th:block th:text="${CSSProcessor.addCSS("/css/main.css")}"/>
    </head>
    

    And the second way is:

    <head th:fragment="publicSiteHeader" th:inline="text">
    
        <title>SOME TITLE</title>
    
         [["${CSSProcessor.setDebugCaller("Public")}"]]
         [["${CSSProcessor.setSiteRegion("public")}"]]
         [["${CSSProcessor.addCSS("/css/main.css")}"]]
    </head>
    

    For natural template processing second option is more preferable. More info about inlining can be found here: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#inlining

    0 讨论(0)
  • 2020-12-16 22:26

    Thymeleaf does not work like JSP. It works by extending existing HTML elements with new attributes prefixed by "th:". And you can reference variables (and therefore call method on them) only in theses extra-attributes.

    E.g. <p th:text="${contentOfTheParagraph}" /> will work with thymeleaf

    But <p>${contentOfTheParagraph}"</p> will not.

    0 讨论(0)
  • 2020-12-16 22:30

    You can call methods via thymeleaf but it is not a good practice. The thymeleaf has different philosophy than JSP - it tries to use valid HTML templates. And to be honest: Calling methods in JSP is not good practice as well. But I am not your judge, so to call a method use non visible span or div, try something like:

    <span th:text="${myvariable.myfunct()}" />
    
    0 讨论(0)
提交回复
热议问题