isaac
isaac

Reputation: 1

Get full URL with parameters in Thymeleaf?

I've got a paginated list of cars, on a Spring Boot server, with the parameters sort, range, desc, page, etc to filter and sort by and am generating the URL in Thymeleaf that looks like:

example.com/cars?page=5&sort=mileage

I am wanting to be able to add more parameters to a URL with a few of these already but I'm quite new to this and don't really know how to get the current URL with all the parameters to add more params without losing the previous ones look like

example.com/cars?page=5&sort=mileage&desc=true

I've found an answer to do something like this on Spring but would ideally want to do it on the Thymeleaf template, is this possible?

Get full current url thymeleaf with all parameters

I found that you can get hold of specific parameters in Thymeleaf using ${param.sort} to get hold of the param sort, could something similar to this get hold of all the params currently?

Thanks

Upvotes: 0

Views: 1113

Answers (1)

RiZKiT
RiZKiT

Reputation: 2511

If someone is still looking for a thymeleaf template only solution, you could use ${#request.getRequestURI()} with ${#request.getQueryString()} and add your additional parameters via concatenation:

<a th:href="@{${url}}" th:with="url=${#request.getRequestURI()+'?'+#request.getQueryString()+'&foo=bar'}">Link</a>

If you need to escape query parameters, you can use #uris.escapeQueryParam():

<a th:href="@{${url}}" th:with="url=${#request.getRequestURI()+'?'+#request.getQueryString()+'&foo='+#uris.escapeQueryParam('b a r')}">Link</a>

Some further details:

  • You have to use th:with, otherwise the parser will throw TemplateProcessingException: Access to request parameters is forbidden in this context. in newer thymeleaf versions.
  • It also works when the current query is empty, the url generator will create a valid url, in my example including one ? and no & in the query part.

Upvotes: 0

Related Questions