如何在百里香片段中设置变量? [英] How to set variables in a thymeleaf fragment?

查看:22
本文介绍了如何在百里香片段中设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Thymeleaf 是为渲染视图而制作的,但是我只是想知道是否有任何方法可以在 Thymeleaf 片段的请求范围内设置变量?

我有一个非常大的条件表达式,我必须在整个应用程序中重复很多次,所以如果我可以在主布局中设置一个变量然后在所有其他子片段中重用它会非常有帮助.

我知道使用 Spring 拦截器并在模型中设置变量,但我不想这样做.

请指教.

谢谢

废话

解决方案

在片段模板中,定义带参数的片段:

<p th:text="${myvariable}"></p>

在布局模板中,包含指定该变量的片段:

<div th:include="template :: myfragment(${variable})"></div>

然后将变量传递给片段模板.

I understand Thymeleaf is made for rendering the views however, I just wanted to know if there is any way to set a variable may be in request scope in a Thymeleaf fragment?

I have a very large conditional expression that I have to repeat a lot of times across the application so it will be really helpful if I can set a variable in main layout then reuse it in all other child fragments.

I am aware of using a Spring interceptor and setting the variable in model but I prefer not to.

Please advise.

Thanks

Prash

解决方案

In the fragment template, define fragment with parameters:

<div th:fragment="myfragment(myvariable)">
    <p th:text="${myvariable}"></p>
</div>

and in layout template, include fragment with that variable specified:

<div th:include="template :: myfragment(${variable})"></div>

Then variable is passed to the fragment template.

这篇关于如何在百里香片段中设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆