Difference between "if" and "cond"

Found something curious:

  1. Cond:

<img src="{{ cond (eq (printf "%T" .) "*resource.Image") (.Fill "960x480").RelPermalink . }}" alt="{{ $title }}">

On cases with . isn’t a *resource.Image i get an error when .Fill is for example executed on a string. The error itself maybe correct, but with this condition set, .Fill shouldn’t be executed.

If i rewrite this with if-else everything is working fine.

<img src="{{ if eq (printf "%T" .) "*resource.Image" }}{{ (.Fill "960x480").RelPermalink }}{{ else }}{{ . }}{{ end }}" alt="{{ $title }}">

Shouldn’t “if” and "case have the same behaviour in my case?

No, it seems that if delimits actual blocks that are executed or not depending on the condition, while cond parses the possible outcomes at the same time it evaluates the condition (that’s because that’s how Go templates work).

I stumbled upon the same issue a while back regarding optional shortcode params :slight_smile:

This should probably be added to the cond documentation if you feel like it!

+1

It is not just the cond.

I’m pretty used to


which does not apply for
https://golang.org/pkg/text/template/#hdr-Functions
and, or
=> All the arguments are evaluated.

So a note on this “no Short-circuit_evaluation” in


would be useful for some people.

example: or (true) (div 1 0) throws an error in hugo templates

@cmal I’m going to add this to the docs today

2 Likes