duanduan8439 2018-09-12 00:09
浏览 118

在Hugo中使用字符串在键中查找数据

I'm trying to create a HUGO-based API documentation site which reads JSON schemas, and prints them in HTML.

I'm almost there, but I'm stumped on how exactly to pass in the data I want to a partial.

Given a standard JSON schema file, such as the following:

{"paths": {
  "/auth/login": {
    "get": {
    "operationId": "login",
    "responses": {
      "200": {
        "description": "",
        "schema": {
          "ref": "#/definitions/loginResponse"
        }
      }
    }
  },
},
"definitions": {
  "loginResponse": {
    "type": "object"
  }
}}

I'd like to display the details of that path, and then render a partial using the schema definition in "ref". I found a way to read that ref param and parse it into a reference for the definition. "Target" below looks like:

Target: .definitions.loginResponse

{{ range $path, $methods := .paths }}
  <h4>{{ $path }}</h4>

  {{ range $method, $items := $methods }}
    <h5>{{ $method }}</h5>
    <ul>
      {{ range $status, $info := .responses }}
        <li>
          <div>{{ $status }}</div>
          <h6>Ref: {{ $info.schema.ref }}</h6>
          <p>Target: {{ $target := (printf ".definitions.%s" (index (findRE "[^/]+(/?$)" $info.schema.ref) 0))}}</p>
          <div>{{ partial "schema" $target }}</div>
        </li>
      {{ end }}
    </ul>
  {{end}}
{{end}}

The trouble is, $target is a string. In Javascript, I'd just be able to pass it in as a key to get that object param: schema["definitions.loginResponse"].

No such luck in HUGO, however. I simply can't find a way to go from that target key string to the actual param.

Help! Am I missing something obvious? Am I going about this all wrong?

  • 写回答

2条回答 默认 最新

  • douchao1957 2018-09-14 21:05
    关注

    I think you need to use dict https://gohugo.io/functions/dict/

    Your {{ partial "schema" $target }} can be changed to {{ partial "schema" (dict "target_name" $target) }}

    In the "schema" partial, you can access value with "{{ .target_name }}"

    评论

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?