You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GoHugo中如何用正则判断当前路径匹配categories等路由模式

问题排查

你之前的写法不生效是因为eq是全等比较函数,无法识别通配符*的匹配规则,要实现路径前缀匹配可以用以下两种方案:

方案1:前缀匹配(更简单,适合大多数场景)

直接用Hugo内置的hasPrefix函数判断Permalink是否以分类/标签路径前缀开头即可:

{{- $categoryPrefix := "categories/" | absURL -}}
{{- $tagPrefix := "tags/" | absURL -}}
{{ if hasPrefix .Permalink $categoryPrefix }}
    <h4 class="mb-3 text-dark font-weight-bold">
        Showing posts with <mark>{{.Title}}</mark> category
    </h4>
{{ else if hasPrefix .Permalink $tagPrefix }}
    <h4 class="mb-3 text-dark font-weight-bold">
       Showing posts with <mark>{{.Title}}</mark> tag
    </h4>
{{ end }}

方案2:正则匹配(更精准,可限定路径格式)

如果需要严格匹配categories/xxx/这种末尾带斜杠的路由格式,用findRE正则匹配函数实现:

{{- $catPattern := print (absURL "categories/") `.*?/$` -}}
{{- $tagPattern := print (absURL "tags/") `.*?/$` -}}
{{ if findRE $catPattern .Permalink }}
    <h4 class="mb-3 text-dark font-weight-bold">
        Showing posts with <mark>{{.Title}}</mark> category
    </h4>
{{ else if findRE $tagPattern .Permalink }}
    <h4 class="mb-3 text-dark font-weight-bold">
       Showing posts with <mark>{{.Title}}</mark> tag
    </h4>
{{ end }}

正则说明:.*?/$表示匹配任意字符直到路径末尾的斜杠,完全符合你需要的路由格式要求。


内容的提问来源于stack exchange,提问作者mhannani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 15:51:04