1

Inside Hugo templates, I'm aware that you can call a function using function param:

{{ singularize "cats" }}

but in the documentation, I'm also seeing you can also do:

{{ "cats" | singularize }}

I've never encountered this way of calling functions (inside languages like Ruby/Python). Is this Go-specific, or just Hugo-specific? How is this way of calling a function called? Also, can you do it if you have more than 1 type of argument?

icza
  • 389,944
  • 63
  • 907
  • 827
anemaria20
  • 1,646
  • 2
  • 17
  • 36
  • Hugo uses Go's standard template library, which is well-documented: https://golang.org/pkg/html/template/ – Adrian Dec 18 '18 at 14:20
  • The above is mentioned in the first sentence of the first section of Hugo's own template docs: https://gohugo.io/templates/introduction/ – Adrian Dec 18 '18 at 14:21
  • Actually, there is a similar feature in Django templates called filters. – Mad Wombat Dec 18 '18 at 15:33

1 Answers1

4

That is a feature of the Go template engine, although it's not a new idea, if you used unix systems, you can do the same in shell commands (think of e.g. ls |more).

It's called "chaining": you specify a sequence of commands, and the output of each is used as the input of the next in the chain.

It's documented at text/template:

A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

The Go template engine only allows you to register and call functions and methods with a single return value; or 2 return values of which the second must be of type error (which is checked to tell if the call is considered successful, and non-nil errors terminate the template execution with an error). So you can't chain commands that have multiple return values, and you can't specify tuples to pass multiple values to functions having multiple parameters.

For more about pipelines, see golang template engine pipelines

icza
  • 389,944
  • 63
  • 907
  • 827