Adding writable context

See:

This is work in progress (or: it works fine, but missing tests and polish, and I wanted to discuss the API here).

I’ve missed something similar to this, and I have seen others shouting out about this too. Due to a limitation in Go templates, the variable scopes makes it impossible to use counter variables and similar.

I have added a Ctx struct to Node and Page with 3 simple methods, Add, Set and Get:

{{ .Ctx.Add "a1" 12 }}
{{ .Ctx.Get "a1"  }} // => 12
{{ .Ctx.Add "a1" 1 }} 
{{ .Ctx.Get "a1"  }} // => 13

{{ .Ctx.Add "a2" "AB" }}
{{ .Ctx.Get "a2"  }} // => AB
{{ .Ctx.Add "a2" "CD" }}
{{ .Ctx.Get "a2"  }} // => ABCD

{{ .Ctx.Set "v1" 123 }}
{{ .Ctx.Get "v1"  }} // => 123

I believe this should be both simple enough and cover most needs?

  • The key is string
  • The value can be anything

So the Add operation has some limitations, but works with the builtin numeric types and strings.

There were definitely places that I wanted to be able to use a counter, so this would be great. The Add function on strings is a little different at first glance, but would work well for concatenating strings for a single tag or something.

The Add function with strings is a little weird, and a side effect - I guess it’s gonna be abused more than used (Add works the same behind the scenes as the “add” template function).

There are many subtle use cases for this, one that pops up is: I have a Twitter shortcode. This depends on a external JS, but I only want to include that once …

I have also seen several posts here and other places about it.

This will make a number of things easier for theme writers, too.

how can I use it? in my section template {{ .Ctx.Add “a1” 12 }} print

ERROR: 2015/01/28 Error while rendering section blog: template: section/blog.html:6:7: executing "section/blog.html" at <.Ctx.Add>: Ctx is not a field of struct type *hugolib.Node

i build hugo from https://github.com/bep/hugo/tree/feature/rendering-context

Yes - that is correct. So you did something wrong with the build.

Now it’s merged to master … but renamed Scratch.

Thanks!