Im using thymeleaf with spring mvc. I want add a language param to change locale. I did it this way:
<a th:href="@{${currentUrl}(lang='es_ES')}" th:if="__${#locale}__ != 'es_ES'" >Sp</a>
<a th:href="@{${currentUrl}(lang='en_US')}" th:if="__${#locale}__ != 'en_US'" >Eng</a>
But in some views I have params in the URL. How I can add the parameters?
I know how to add when I meet the specific parameter:
<a th:href="@{${currentUrl}(fooParam = ${fooValue}, lang='es_ES')}" th:if="__${#locale}__ != 'es_ES'" >Sp</a>
But I know neither the number and name of all parameters in all views. How I can get all the parameters of the current url?
You can try to create an utility service for building the params part of your URL. The utility method will get input from a List and build a String through StringBuffer. The result will be a String written as when you write param manually. Now you can use the Pre-Parser syntax built in thymeleaf to call the utility and build your final url.
Here the example:
Utility Service
@Service("thymeleafUtilsService")
public class ThymeleafUtilsService
{
public String buildMultiParamPartUrl(List<String> paramNames)
{
StringBuffer sb = new StringBuffer(0);
for ( String paramName : paramNames )
{
if ( sb.length() >= 0 )
{
sb.append(",");
}
sb.append(paramName).append("=${").append(paramName).append("}");
}
return sb.toString();
}
}
Controller for testing it
@Controller("multiParamLinkController")
@RequestMapping(value = "/multiParamLink")
public class MultiParamLinkController
{
@RequestMapping(value =
{ "/",
"" }, method = RequestMethod.GET)
public String testMultiParamsGenerator(Model model)
{
List<String> paramNames = new ArrayList<>();
paramNames.add("fooValue");
paramNames.add("barValue");
paramNames.add("lang");
model.addAttribute("fooValue", "foo");
model.addAttribute("barValue", "bar");
model.addAttribute("lang", "US_us");
model.addAttribute("paramNames", paramNames);
return "multiParamLink/multiParamLink.html";
}
}
HtmlTemplate for Test:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<a th:href="@{${currentUrl}(__${@thymeleafUtilsService.buildMultiParamPartUrl(paramNames)}__)}">myLink</a>
<h1>Result</h1>
<pre th:inline="text">[[@{${currentUrl}(__${@thymeleafUtilsService.buildMultiParamPartUrl(paramNames)}__)}]]</pre>
</body>
</html>
this is what you get with the example:
You can now customize this example to suit your code, like parsing a Map instead of List or String...