简体   繁体   中英

Thymeleaf #{property_name} - which file to create properties reference by > 1 template

I'm using Thymeleaf and need a property value in multiple templates (not a common header or footer).

The docs say if we have a template a.html the messages go in a.properties or a_en.properties .

What if I have a property, say:

test_property=This is a common message: {0}

That I want to use in the template a.html and b.html . What properties file does it go in? Is there a global properties file I can create or can I configure Thymeleaf to load a global properties file?

I'm going by these docs:

http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#messages

It seems like this would be a thing that this would support...

Thymeleaf docs ( Externalizing Messages ) says:

The location of externalized text in Thymeleaf is fully configurable, and it will depend on the specific org.thymeleaf.messageresolver.IMessageResolver implementation being used. Normally, an implementation based on .properties files will be used, but we could create our own implementations if we wanted, for example, to obtain messages from a database.

So, You can use one of the following ways:

1. Create a custom implementation for org.thymeleaf.messageresolver.IMessageResolver interface.
Reference: StandardMessageResolver

2. Thymeleaf uses OGNL as default. According to OGNL docs :

You can refer to a static field using the syntax @class@field. The class must be fully qualified.

So, Create a JAVA class that contains these static string messages and then call them in thymeleaf templates:

th:text="${@com.example.yourpackagename.Constants@STRING_KEY}"

3. If you are using spring/spring boot, you can simply use message.properties file located in resources folder.

4. Create a fragment html page that uses your desired message(s) and then call this fragment in your templates and then use .properties files (in the same folder as fragment file) for this fragment html file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM