Relative th:include paths

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Relative th:include paths

mjog
Hi,

How can I use th:include in a template using a relative path?

I'm converting an existing webapp to Thymeleaf. The template directory structure looks like this:

templates/common.xml
templates/module1/common.xml
templates/module1/list.xml
templates/module1/view.xml
templates/module1/submodule1/common.xml
templates/module2/common.xml
...

While list.xml and view.xml are the templates used when rendering views, the common.xml file at the same directory level contains fragments to be included in both. The common.xml file in the root template directory contains site-wide fragments, included in most other templates I'd like to retain this structure, but I don't want to have to specify absolute paths since the full path would need to be repeated for every td:include in the view templates and can be quite long, creating a lot of useless repetition.

The only thing I have found that works is the following:

    <p th:include="__${execInfo.templateName}__/../common::fragment_name"/>

Which is something of an abomination, being as long or longer than if an absolute path was used. More specifically, why doesn't the following just work?

    <p th:include="common::fragment_name"/>

Thanks,
//Mike
Reply | Threaded
Open this post in threaded view
|

Re: Relative th:include paths

Emanuel
Administrator
I'm guessing it's a design decision.  Thymeleaf template paths aren't really absolute or relative - they're constructed from a combination of prefix + template name/path + suffix (where prefix and suffix are configured on the template resolver).

If you want to create a path-relative fragment inclusion mechanism, then I think you can do that by creating a custom processor that extends the class that backs the th:include processor, although the details of how to go about it escape me (you'll have to resolve the current template to a path).
Reply | Threaded
Open this post in threaded view
|

Re: Relative th:include paths

danielfernandez
Administrator
In reply to this post by mjog
th:include and th:replace simply require you to specify your template locators in the way that your template resolver(s) understand.

Most template resolver implementations provided by thymeleaf allow you to specify a prefix and a suffix to be added to all your template locators so that you don't have to specify them in your th:include/th:replace attributes.

That way, if you set your prefix to point to your "templates/" folder and your suffix to ".xml", you should be able to access all your templates like "common", "module1/common", "module1/list", etc.