Search code examples
javaspringthymeleaf

Ignore empty params in href in Thymeleaf


So I have this href:

th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, search=${param.search})}"

Which works fine, but I want to make the url look cleaner by hiding the search param, if it is empty.

E.g.:

  • param.search = 'test' => url = "../apps/role/varAttr?search=test"
  • param.search = '' => url = "../apps/role/varAttr"

I stumbled upon this post, however nothing I tried could make it work for my purposes. It could be that the pathvariable has something to do with it, but really I'm clueless.

I tried:

th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, __(${param.search}=''?','search=${param.search})__)}
th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, __(${param.search}=''?,search=${param.search})__)}

as well as some more desperate attempts.

Edit: I use Thymeleaf version 3.0.11.

Solution: The marked solution, didn't exactly work for me, but this did. I just left out the first pair of "__" for the pathVar.

th:with="search=${param.search}"
th:href="@{/apps/role/{pathVar}(pathVar=${var.attribute}, __(${#strings.isEmpty(search)} ? '' : ('search=' + ${search}))__)}"

Solution

  • You can try like this:

    <a th:with="search=${param.search}"
       th:href="@{/apps/role/__${pathVar}__(pathVar=${var.attribute}, __(${#strings.isEmpty(search)} ? '' : ('search=' + ${search}))__)}">
       Click Url
    </a>
    

    If the search parameter does not exist or is empty, it will not add it. I did this with *Thymeleaf version 3.0.12.