Arthur
Arthur

Reputation: 3473

Thymeleaf didn't see objects from Spring

My template do not see objects, passed from Spring.

My code:

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's code:

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

    }

}

Main template's code:

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

Fragment's code:

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

As result I do not see value of the object pageTitle, but I see in page output code like

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

        <title>${pageTitle}</title>

Why thymeleaf didn't paste value of the pageTitle to between title tag's open and close?

The same code works good with JSP, but do not work with thymeleaf.

Upvotes: 0

Views: 452

Answers (1)

kulatamicuda
kulatamicuda

Reputation: 1651

Thymeleaf is not JSP, so that's why your template does not work as you expect.

Look here http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts and use something like:

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

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

Edited - my solution is for localised texts which is good practice anyway. if you want to use content of variable than use $.

Upvotes: 1

Related Questions