Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking up data by key in Hugo with a string

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?

like image 384
G Amini Avatar asked Sep 12 '18 00:09

G Amini


1 Answers

Figured it out! In case anyone runs into this same problem, param lookup is done simply with Hugo's index function.

{{ $target := index $info.schema "$ref" | findRE "[^/]+(/?$)" }}

With $target, under the parent context, it's merely {{ index . $target }}.

like image 59
G Amini Avatar answered Sep 25 '22 09:09

G Amini