首页 > 解决方案 > 如何覆盖文件但跳过一个特定的文件名

问题描述

我正在编写一些博客代码(由其他人编写),它将所有帖子列出到主 index.html 文件中。我想从这个列表中排除一个文件(welcome.md)。我相信这是执行此操作的相关代码-

{{$l := len .}}
{{range $i, $e := .}}         
<h3><a href="/{{$e.Title | slug}}.html">{{$e.Title}}</a></h3>

可能吗?

更新 - 这是我的完整代码,我在上面遗漏了一些 -

{{define "title"}}
  Test
{{end}}

{{define "content"}}
<h1>Heading</h1>

{{$l := len .}}
      {{range $i, $e := .}}
      {{- if ne $e.Title "welcome" -}}        
            <h3><a href="/{{$e.Title | slug}}.html">{{$e.Title}}</a></h3>
            {{- end }}
            <small>
              <em>
              {{$e.Written.Format "Jan 2, 2006"}}&nbsp;
              Tags:  {{range $e.Tags}}
              <a href="/tags/{{. | slug}}.html" title="Posts Tagged {{.}}">{{.}}</a>&nbsp;
                {{end}}
              </em>
            </small>
            {{(printf "%s </br><small>[Read more](/%s.html)</small>" ($e.Content | summary) (.Title | slug)) | html}}

{{end}}
{{end}}

标签: gogo-templates

解决方案


您可以{{if ...}}在模板中使用。结合ne函数(对于“不等于”):

{{range $i, $e := .}}
  {{- if ne $e.Title "welcome" -}}
<h3><a href="/{{$e.Title}}.html">{{$e.Title}}</a></h3>
  {{- end }}
{{ end }}

游乐场示例

但是,如果您可以控制数据模型,感觉也许您可以使其更通用。也许每个帖子上都有一个标志ExcludeFromIndex或类似的东西:

{{- if !$e.ExcludeFromIndex -}}

这样,如果您添加更多“特殊”页面,则无需为每个页面继续添加 if 语句。只是一个想法。


推荐阅读