Thymeleaf没有看到Spring的物品

时间:2015-01-21 11:26:48

标签: java spring

我的模板看不到从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("pageTitle", "TITLE!!!!!!!!!!!!!!");
        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>${pageTitle}</title>

        <!--[if lte IE 8]>
    <script src="<?= SITE_TEMPLATE_PATH ?>/js/html5shiv.js"></script>
    <![endif]-->
    </head>
    <body>

    </body>
</html>

结果我没有看到对象pageTitle的值,但我在页面输出代码中看到如

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

        <title>${pageTitle}</title>

为什么百万富翁没有将pageTitle的值粘贴到标题标签的打开和关闭之间?

相同的代码适用于JSP,但不适用于百里香。

1 个答案:

答案 0 :(得分:1)

Thymeleaf不是JSP,所以这就是为什么你的模板不能按预期工作的原因。

在这里查看http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts并使用类似的内容:

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

    <title th:text="#{pageTitle}">page title</title>

已编辑 - 我的解决方案适用于本地化文本,无论如何这都是很好的做法。如果你想使用变量的内容而不是使用$。