Reputation: 1444
I have two html templates which do same function, but handled by two different controllers:
1st html handled by moderator controller
<form th:action="@{/moderator/new-user-form}" th:object="${caltest}" method="post"
enctype="multipart/form-data" class="form-validate form row">
<!-- some code -->
</form>
2nd html handled by admin controller
<form th:action="@{/admin/new-user-form}" th:object="${caltest}" method="post"
enctype="multipart/form-data" class="form-validate form row">
<!-- some code -->
</form>
As you can see these templates differ only by action
url:
th:action="@{/someurl}"
Is it possible to use the same template with dynamic url from different controllers?
Upvotes: 1
Views: 2688
Reputation: 20487
There are many different ways to do this... the simplest, is to use the same template in the controllers, and in each controller pass a variable that contains the correct action.
For example:
// Moderator controller
@RequestMapping(value = "/moderator")
public String moderator(Map<String, Object> model) {
model.put("action", "/moderator/new-user-form");
return "new-user-form";
}
// Admin controller
@RequestMapping(value = "/moderator")
public String moderator(Map<String, Object> model) {
model.put("action", "/admin/new-user-form");
return "new-user-form";
}
And in the html
<form th:action="@{${action}}">
If that isn't suitable, you could turn the form itself into a fragment, and then pass the action as a parameter. Something like this:
<!-- Fragment -->
<form th:fragment="userform (action)" th:action="@{${action}}">
.
.
.
</form>
<!-- Including the fragment -->
<div th:replace="fragments/userform :: userform(action='/admin/new-user-form')" />
<!-- or -->
<div th:replace="fragments/userform :: userform(action='/moderator/new-user-form')" />
Upvotes: 3