Is there a way to define custom Go Template Actions

625 views Asked by At

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).

1

There are 1 answers

0
KernelDeimos On

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 the Tree.action method in parse.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.