Hacker News new | ask | show | jobs
by sepbot 3416 days ago
I always considered the actual template to be the presentation layer relative to the templating context. Having worked on large scale applications it has become apparent to me that performing business logic in the presentation is not the way to go. In my opinion, a templating application should be architectured in such way that your data is transformed to exactly how you want it to be presented prior to it getting to the presentation layer. Up in presentation, you should really only have to worry about checking if a condition is true or false or iterating a collection. From what I have seen of Golang, some (not all) design decisions seem to have been made to make it difficult to make such mistakes easily, so I would not be surprised if making it difficult to do logic in the template was a conscious decision.
1 comments

While I agree in theory, I can't stand that in practice :).

For example, let's say I want to show a usage stat, I'd pass something like { usage: 100, limit: 1000 } to the template engine. Let's say I want to add a percentage. I believe the calculation should be on the presentation layer. That's how I decide to present this particular data.

Go templates lack that functionality for no good reason. And if I'm gonna calculate that on the backend, why exactly am I using a template engine? I'd concatenate strings.

Actually you can do function calls on Go templates [1], and indeed this is what is done in practice. Libraries got written to do this, and badly integrated [2].

You will quickly find if you use this that it's in fact worse: go templates have LISP syntax. A set of atoms, specified in reverse Polish notation, doing function application to all but the first atom.

[1] https://golang.org/pkg/text/template/#Template.Funcs

[2] https://github.com/Masterminds/sprig

Yeah this is the reason I went ahead and wrote the template engine I mentioned in the parent comment. It compiles down to go templates. I inject generic math functions [1] and convert an expression like 4 + 5 * 3 to go template function calls. It's ugly but the compiler generates it so whatever :)

[1] https://github.com/eknkc/amber/blob/master/runtime.go