使用百里香的条件属性 [英] Conditional attribute using thymeleaf
问题描述
我知道如何在jstl的标记内创建条件属性:
I know how to make a conditional attribute inside a tag on jstl:
<body <c:if test="${userCreated}"> onload="somejavascriptfunction()"</c:if> >
但是我该如何使用百里香叶呢?
But how do I do it using thymeleaf?
IndexController
IndexController
@RequestMapping("/register")
public String register(UserEntity user, @RequestParam String repeatedPassword, RedirectAttributes redirectAttributes) {
user.setAdmin(false);
userFacade.create(user);
redirectAttributes.addFlashAttribute(Constants.USER_CREATED, true);
logger.info("Usuario criado");
return "redirect:/login";
}
到目前为止,我发现的唯一解决方案就是这样做
So far the only solution I found was to do it like this
<script type="text/javascript" th:if="${userCreated}">
$(document).ready(function() {
somejavascriptfunction()
});
</script>
但这似乎并不是最好的方法.那么,如何在百里香上的属性上做一个if语句呢?
But that doesn't seem to be the best way to do it. So how do I make an if statement for an attribute on thymeleaf?
推荐答案
考虑添加一个使用以下格式的条件类,这确实有点违反直觉:
It's really kind of counter-intuitive, considering to append a conditional class you use the following format:
<div th:classappend="${userSlug != null}?has-slug">
要附加条件属性,请将条件放在属性的值上,如下所示:
In order to append a conditional attribute, you put the condition on the attribute's value, like so:
<div th:attrappend="data-path=${userSlug != null}?@{/myaccount/__${userSlug}__}">
如果userSlug为null,则前一条语句的计算结果为:
If userSlug is null, the previous statement will evaluate to:
<div>
如果userSlug为 not null,则该语句的计算结果为:
If userSlug is not null, the statement evaluates to:
<div data-path="/myaccount/my-slug">
这篇关于使用百里香的条件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!