【问题标题】:Thymeleaf didn't see objects from SpringThymeleaf 没有看到 Spring 的对象
【发布时间】:2015-01-21 11:26:48
【问题描述】:

我的模板看不到对象,从 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);

    }

}

控制器代码:

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

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

同样的代码适用于 JSP,但不适用于 thymeleaf。

【问题讨论】:

    标签: java spring


    【解决方案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>
    

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

    【讨论】:

    猜你喜欢
    • 2017-09-12
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2018-06-15
    • 2017-05-26
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多