Revisiting template debugging via printf

I’ve been looking at {{ printf( "%v" ...) }}. It works well for simple variables, but when I’m looking at a larger level, it’s just too hard for me to read.

I’ve been looking at using reflect in a pretty-print function. It’s crufty.

I tried adding String() methods to Node, Page, etc, that wrap up the output in <li>...</li> pairs doesn’t feel like a very clean solution.

My favorite is using the JSON marshaling function. Except for the (expected) quoting, it does what I’m looking for. It’s a simple function, too:

func DumpVar(v interface{}) string {
	j,err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return ""
	}
	return string(j)
}

Mapping “dumpvar” to DumpVar in tpl/template_funcs.go allows for:

<code><pre>{{ dumpvar . }}</pre></code>

Which gives me something like:

{
  "Version": "0.16-DEV",
  "Generator": "\u003cmeta name=\"generator\" content=\"Hugo 0.16-DEV\" /\u003e",
  "CommitHash": "",
  "BuildDate": ""
}
"\u003cmeta name=\"generator\" content=\"Hugo 0.16-DEV\" /\u003e"
{
  "RSSLink": "http://localhost:1313/index.xml",
  "Data": {
    "Pages": [
      {
        "Params": {
          "series": [
            "using"
          ]
        },

And I can create a partial to wrap the code+pre for me.

Is this a general enough solution or should I keep banging away on reflect?

3 Likes

I know this was a long time back… but are you still working on this? I have some interest in this type of debugging.

I believe this, or something like it would be helpful in understanding what Hugo and/or the Go template system is doing.

Something simpler would be nice as well, like dumping nested data:

main
menu
apple
imac.html
mini.html
macpro.html

…that sort of thing. taxonomies, menus, etc.

The PR was rejected. The concept didn’t add value.

The dumpvar func above is the same as doing:

<code><pre>{{ . | jsonify }}</pre></code>

There are, however, two problems with the above:

  • It doesn’t handle cyclic references. It will not panic, but you will not get .Page.Site and some other entities.
  • It doesn’t handle funcs – and that will miss out on a lot

We can make some custom marshaler for this, but that is work, and I want to wait with that until we have a stable object model.

Yep. That’s part of why the concept didn’t add value. It needed much more work.