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
@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>
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?
Using Switch Case Statement - th:switch Attribute To achieve similar to if-else condition in Thymeleaf , we can use th:switch attribute. Thymeleaf at the first step will evaluate ${condition} expression and if the value is true it will print p tag with TRUE text.
We can use the th:with attribute to declare local variables in Thymeleaf templates. A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it.
Thymeleaf relies on two attributes to render elements conditionally, and they are th:if and th:unless . Both of these attributes take a boolean expression and try to render as their names suggest. That is, The thymeleaf th:if attribute renders the element only if the boolean condition is true .
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}__}">
If userSlug is null, the previous statement will evaluate to:
<div>
If userSlug is not null, the statement evaluates to:
<div data-path="/myaccount/my-slug">
Have you tried creating the onload attribute using the th:attr processor? I know there are several processors which will not render the attribute if the outcome is null. I'm not sure if this applies on the attr processor
<body th:attr="onload=${doOnload ? 'somejs()' : null}"> </body>
I dont have a testcode available here but this could work. Alternatively you could return an empty onload attribute.
Else, I don't see an issue with your second approach using a conditonal script tag. I do this quite often in my components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With