CloudyKit / jet

Jet template engine
Apache License 2.0
1.26k stars 106 forks source link

Safe access to values in map #204

Closed StephanSchmidt closed 1 year ago

StephanSchmidt commented 1 year ago

I want to write a block that takes an argument, e.g. "A.B.C" and then checks if .A.B.C (in a map) is there and writes the value otherwise it writes "-".

{{ yield field(key="A.B.C") }}

but I struggle with meta access to context, and I struggle with checking if A.B.C exists in the context, e.g. {{ try }} {{ .A.B.C }} {{ end }} results in an unexpected {{ end }}.

StephanSchmidt commented 1 year ago

Solved by using gjson instead of the jet access.

sauerbraten commented 1 year ago

I think what you were looking for is the isset built-in function: https://github.com/CloudyKit/jet/blob/master/docs/builtins.md#isset Search this file for "isset" for some examples: https://github.com/CloudyKit/jet/blob/master/eval_test.go

StephanSchmidt commented 1 year ago

Thanks. Yes, I was playing with isset too, but couldn't get it to work. Especially if there were null from the database (JSONB postgres).

Also I struggled with creating a function so I don't have to use {{ if isset(...) }} for every field access as described in the ticket.

As I wrote, I use gjson with it's pathing now and it works fine (I copy a parsed raw message from the database to the data object for the template).