Is there a way to define custom "Actions" (like range, if, block, etc) with either text or html go templates. I would like to achieve something like the following:
{{ component "blog_post" . }}
{{ template "title" . }}
{{ component "content" . }}
My Content
{{ end }}
{{ end }}
Where "component" is my custom action.
I have achieved the above functionally using custom functions but it is pretty clunky and hard to read. I am particularly interested in the ability to use a custom action that takes both a normal argument (such as .
) as well as arbitrary "children" (much like a react component).
This is not possible in the current implementation of Go templates.
Actions are handled by the internal
text/template/parse
package, and are all defined in https://golang.org/src/text/template/parse/node.go. You will find that there is no mechanism for creating new actions, as theTree.action
method inparse.go
has a hardcoded switch case for them.This is sad because the
text/template
package has a lot of missed opportunities for reusable features. For example, there's an entire built-in LISP parser that's unusable unless you use it through the template parser.