thymeleafspring-thymeleaf

How to generate href-links containing '#' with ThymeLeaf?


in my template, I must generate a link of type

<a href="http://myhost/myapp/#/products/12345/details">. . .</a>

'12345' is a variable part.

The link is a "deep link" to details of the product with the ID=12345. The '#' in the URL must be there because the web framework that displays the details wants it so (I think it's a single page web app).

If I have this in the template:

<a th:href="@{http://myhost/myapp/#/products/{productId}/details(productId=${product.id})}">. . .</a>

then the generated link looks like

.../myapp?productId=12345#/products/{productId}/details

i.e. the part beginning with '#' is fist cut off and then appended verbatim; the parameter is appended to the URL as a query string (with '?').

If I have this in the template (i.e. I make the hash symbol part of the variable so that this part of th URL is not cut off):

<a th:with="productLink=${'#/products/' + product.id + '/details'}"
   th:href="@{http://myhost/myapp/{productLink}(productLink=${productLink})}">. . .</a>

then I get almost what I want, but the '#' in the URL is encoded as '%23':

<a href="http://myhost/myapp/%23/products/12345/details">. . .</a>

How can I generate the URL as it should be, i.e. with the hash sign and the product id at correct place -- see the start of the question.

The application is a SpringBoot based one, if that matters.


Solution

  • If you don't want Thymeleaf to mess with your URL, I would suggest using the regular string functions. You could use literal substitution for example:

    <a th:href="|http://myhost/myapp/#/products/${product.id}/details|">. . .</a>
    

    (Here is why Thymeleaf is messing with your #. It's trying to keep the # at the end of the url. I don't believe there is any way to change how this is working.)