dua55014 2015-11-22 22:22
浏览 47
已采纳

在Go模板中对地图迭代进行排序?

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条回答 默认 最新

  • douhan9191 2015-11-23 01:03
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题