如何从Thymeleaf调用对象的方法?

我的模板看不到从Spring传递过来的对象。

我的代码:

public class PublicModelAndView extends ModelAndView {

@Autowired

TemplateModulesHandler templateModulesHandler;

public void init() {

setViewName("index");

CSSProcessor cSSProcessor = new CSSProcessor();

cSSProcessor.setSiteRegion("public");

super.addObject("CSSProcessor", cSSProcessor);

JSProcessor jSProcessor = new JSProcessor();

super.addObject("JSProcessor", jSProcessor);

templateModulesHandler.setPublicModelAndView(this);

}

}

Contoller的代码:

@SpringBootApplication

@Controller

public class IndexPage {

@Autowired

PublicModelAndView publicModelAndView;

@Autowired

OurServicesBean ourServicesBean;

@Autowired

PortfolioBean portfolioBean;

@RequestMapping(value = "/", method = RequestMethod.GET)

public ModelAndView indexPage() {

publicModelAndView.setTemplate("publicSiteIndexPage");

publicModelAndView.addObject("ourServices", ourServicesBean.getMenu());

publicModelAndView.addObject("portfolioWorkTypes", portfolioBean.getWorkTypes());

publicModelAndView.addObject("portfolioWorks", portfolioBean.getWorks());

return publicModelAndView;

}

}

主模板的代码:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org"

>

<head th:include="headerAndFooter/fragments/header :: publicSiteHeader">

<title></title>

</head>

<body>

hello!

</body>

</html>

片段的代码:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org">

<head th:fragment="publicSiteHeader">

<title>SOME TITLE</title>

${CSSProcessor.setDebugCaller("Public")}

${CSSProcessor.setSiteRegion("public")}

${CSSProcessor.addCSS("/css/main.css")}

</head>

<body>

</body>

</html>

结果,我看到了方法调用的代码,例如

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>SOME TITLE</title>

${CSSProcessor.setDebugCaller("Public")}

${CSSProcessor.setSiteRegion("public")}

${CSSProcessor.addCSS("/css/main.css")}

为什么thymeleaf不调用方法,而是在输出页上打印此文本?在http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html的示例中,方法调用具有相同的语法,例如

${person.createCompleteName()}

相同的代码在JSP中可以很好地工作,但是在百里香中则不能工作。

回答:

可以在Thymeleaf中以两种方式完成此操作:

首先是对Thymeleaf使用special:

<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>

第二种方法是:

<head th:fragment="publicSiteHeader" th:inline="text">

<title>SOME TITLE</title>

[["${CSSProcessor.setDebugCaller("Public")}"]]

[["${CSSProcessor.setSiteRegion("public")}"]]

[["${CSSProcessor.addCSS("/css/main.css")}"]]

</head>

对于自然模板处理,第二个选项更可取。有关内联的更多信息,请参见:http

:

//www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#inlining

以上是 如何从Thymeleaf调用对象的方法? 的全部内容, 来源链接: utcz.com/qa/420395.html

回到顶部