问题描述
限时送ChatGPT账号..所以我的 Thymeleaf 模板中有一个元素,它有一个看起来像这样的链接:
So I have an element in my Thymeleaf template which has a link looking like that:
th:href="@{'/search/'+${searchType}(parameter1=${parameter1}, ... parameter10=${parameter10})}"
根据当前的实现,parameter1...10
可以具有我不想包含在 href
中的值.比如如果是id,可以是-1,表示没有选择id,所以这个参数要省略,以免乱码url字符串,所以用
According to the current implementation the parameter1...10
can have values that I don't want to include in the href
. For example, if it's id, it can be -1, which means that no id chosen, so this parameter have to be omitted to avoid clattering the url string, so instead of
/search/type?parameter1=-1
保持干净
/search/type
如何实现?我试过这个:
How this can be achieved? I tried this:
th:href="@{'/search/'+${searchType}((${parameter1}=='-1'?''parameter1=${parameter1}))}"
但是这个表达式会导致异常:
But this expression causes exception:
org.thymeleaf.exceptions.TemplateProcessingException:无法解析作为表达式:
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression:
我试过了:
th:href="@{'/search/'+${searchType}(parameter1=(${parameter1}=='-1'?'':${parameter1}))}"
但是结果还是不能接受:
But then the result is still not acceptable:
/search/type?parameter1=
那么从 url 中消除不需要的参数的正确方法是什么?
So what is the correct way to eliminate undesirable parameters from the url?
推荐答案
看来我做了更多的研究并找到了方法.关键词是:预处理.这是链接.因此,出于我的目的,以下表达式有效:
Looks like I did more research and found a way. The key word is: preprocessing. This is the link. So for my purposes the following expression works:
th:href="@{'/search/'+${searchType}(__(${parameter1}=='-1'?','parameter1=${parameter1})__,__(${parameter2}=='-1'?','parameter2=${parameter2})__)}"
简短说明:用双下划线包围表达式__(${parameter1}=='-1'?','parameter1=${parameter1})__
,然后被包围的表达式将仅当它评估为非空字符串时才添加.在 url 参数的情况下,','
计算为两个空参数并且不添加.
Short explanation: surround the expression with double underscores __(${parameter1}=='-1'?','parameter1=${parameter1})__
, and then the surrounded expression will only be added if it evaluates to non-empty string. In the case of url parameters ','
evaluates to two empty parameters and not added.
这篇关于Thymeleaf th:href 参数中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论