Skip to content

Ternary operator-like function #3860

@jetwash

Description

@jetwash

TL;DR: I'd like a function similar to the ternary operator in C-like languages.

One thing I've found a bit frustrating with go templates is that you can't really conditionally assign to a variable (other than with default, which is great, but limited). For example, let's say that for a certain page type I want to use the parent's Params for some stuff in my template. Currently, AFAIK I'd need to use a scratch variable:

{{ if eq .Type "assertion" }}
  {{ .Scratch.Set "pageParams" .Parent.Params }}
{{ else }}
  {{ .Scratch.Set "pageParams" .Params }}
{{ end }}
{{ $pageParams := .Scratch.Get "pageParams" }}

What I'd like to do is something like

{{ $pageParams := ternary (eq .Type "assertion") .Parent.Params .Params }}

I'm not overly fond of the name "ternary" since not everyone writing Hugo themes is likely to be familiar enough with a C-like language to even know about the ternary operator. Maybe "when" would make sense, or "cond"? I don't really care about the name, though.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions