Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

thymeleaf - How to pass common data to every page in project

spring-boot-starter-parent 2.4.1

spring-boot-starter-thymeleaf

I have a bunch of constants that I want to be accessible everywhere.

For example I have organized some constants:

public class Constants {
    public final static String LANG = "lang";
}

Here I have a param which I already use in two places: in LocaleResolver and in LocaleChangeInterceptor.

And I need on every page where I include this fragment:

<th:block th:fragment="top" !doctype html>
    <div>
        <a href="?lang=fr">French</a>
        <a href="?lang=en">Английский</a>
    </div>
</th:block>

As we can see, this hardcoded twice. I'd like to avoid such cases.

Is it possible somehow? If a class with static methods is not a good practice, I can use whatever you suggest. Even if such class is preferrable for me, any elegant solution would be highly appreciated.

question from:https://stackoverflow.com/questions/65840788/how-to-pass-common-data-to-every-page-in-project

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can access static variable in Thymeleaf expressions.

<th:block th:fragment="top" !doctype html>
    <div>
        <a th:href="|?${T(Constants).LANG}=fr|">French</a>
        <a th:href="|?${T(Constants).LANG}=en|">Английский</a>
    </div>
</th:block>

(Where Constants is the full path to your class)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...