英文:
Sorted Map Iteration in Go Templates?
问题
我正在使用Hugo静态网站生成器在Go语言中构建一个网站。我想要做的是为我的网页构建一个动态导航栏。
这是我的做法:
在我的config.yml
文件中,我定义了一个链接的映射,我希望它们出现在我的导航栏中,文件的内容如下:
baseurl: "https://www.rdegges.com/"
languageCode: "en-us"
title: "Randall Degges"
params:
navLinks: {"Twitter": "https://twitter.com/rdegges", "Facebook": "https://www.facebook.com/rdegges", "Google+": "https://plus.google.com/109157194342162880262", "Github": "https://github.com/rdegges"}
所以,我在Hugo中还有一个index.html
模板,其中包含一个导航栏,代码如下:
<nav>
<ul>
{{ range sort $title, $link := .Site.Params.navLinks }}
<li><a href="{{ $link }}">{{ $title }}</a></li>
{{ end }}
</ul>
</nav>
上面的代码可以正常工作,但有一个例外:我希望对链接的结果进行排序,而不是每次随机排序。
我知道在Go语言中,映射(Maps)本身没有结构,但是否有一种方法可以以某种方式保留导航元素的原始顺序呢?
谢谢帮助!
英文:
I'm building a website in Go, using the Hugo static site generator. What I'm trying to do is build a dynamic navigation bar for my web pages.
Here's what I'm doing:
In my config.yml
file, I've defined a Map of links that I'd like to appear in my navbar -- here's what this file looks like:
baseurl: "https://www.rdegges.com/"
languageCode: "en-us"
title: "Randall Degges"
params:
navLinks: {"Twitter": "https://twitter.com/rdegges", "Facebook": "https://www.facebook.com/rdegges", "Google+": "https://plus.google.com/109157194342162880262", "Github": "https://github.com/rdegges"}
So, I've also got an index.html
template in Hugo that contains a navbar which looks like this:
<nav>
<ul>
{{ range sort $title, $link := .Site.Params.navLinks }}
<li><a href="{{ $link }}">{{ $title }}</a></li>
{{ end }}
</ul>
</nav>
This above code works correctly, with one exception: I'd like to order the results of my links instead of having them randomly ordered each time.
I know that Maps are not inherently structured in Go -- but is there a way to retain the original ordering of my navigation elements in some way?
Thanks for the help!
答案1
得分: 4
Go模板按键对映射进行排序。如果您想强制使用特定的顺序,请使用切片:
这是YAML代码:
baseurl: "https://www.rdegges.com/"
languageCode: "en-us"
title: "Randall Degges"
params:
navLinks:
- title: Twitter
url: https://twitter.com/rdegges
- title: Facebook
url: https://www.facebook.com/rdegges
...以及模板代码:
<nav>
<ul>
{{ range $link := .Site.Params.navLinks }}
<li><a href="{{ $link.url }}">{{ $link.title }}</a></li>
{{ end }}
</ul>
</nav>
英文:
Go templates sort maps by key. If you want to force a specific order, then use a slice:
Here's the YAML:
baseurl: "https://www.rdegges.com/"
languageCode: "en-us"
title: "Randall Degges"
params:
navLinks:
- title: Twitter
url: https://twitter.com/rdegges
- title: Facebook
url: https://www.facebook.com/rdegges
... and the template:
<nav>
<ul>
{{ range $link := .Site.Params.navLinks }}
<li><a href="{{ $link.url }}">{{ $link.title }}</a></li>
{{ end }}
</ul>
</nav>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论