gonja icon indicating copy to clipboard operation
gonja copied to clipboard

Doesn't support Jinja's for...else syntax

Open yfzhou0904 opened this issue 2 years ago • 1 comments

func TestJinja(t *testing.T) {
	jsonStr := `{"search": "yeno"}`
	c := map[string]interface{}{}
	err := json.Unmarshal([]byte(jsonStr), &c)
	if err != nil {
		fmt.Println(err.Error())
		t.FailNow()
	}
	tmpl := `
{%- set keywords = ['yes', 'hello'] -%}
{%- for w in keywords if w in search -%}
{%- if loop.first -%}
match
{%- endif -%}
{%- else -%}
no match
{%- endfor -%}
`
	tpl, err := gonja.FromString(tmpl)
	if err != nil {
		return
	}
	out, err := tpl.Execute(c)
	if err != nil {
		fmt.Println(err.Error())
		t.FailNow()
	}
	fmt.Println("output:", out)
}

The above code tests whether an input string contains any string (as substring) in a list predefined inside a Jinja template. However, going into the else branch produces an empty output whereas "no match" is expected. The "match" case works though.

https://jinja.palletsprojects.com/en/3.1.x/templates/#for

yfzhou0904 avatar Oct 10 '22 13:10 yfzhou0904

Fixed in https://github.com/NikolaLohinski/gonja/commit/aba64fe9d2d9ca252e91d84b7cf32aec52512b9b

NikolaLohinski avatar Apr 27 '23 06:04 NikolaLohinski