Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example to use args and kwargs function in template. #18

Open
prasad83 opened this issue Aug 22, 2024 · 0 comments
Open

Example to use args and kwargs function in template. #18

prasad83 opened this issue Aug 22, 2024 · 0 comments

Comments

@prasad83
Copy link

In this example, merge_all function will be defined to receive args and kwargs arguments.

tpl, _ := gonja.FromString("<h1>{{merge_all('jack', 'jill', 'jimmy', went='up-the-hill')}}</h1>")
if data, e := tpl.Execute(gonja.Context{
	"merge_all": func(name *exec.VarArgs) (string, error) {
		vals := make([]string, 0)
		l := len(name.Args)
		for i, v := range name.Args {
			if i == l-1 {
				vals = append(vals, "and")
			} else if i > 0 {
				vals = append(vals, ",")
			}
			vals = append(vals, fmt.Sprintf("%v", v.Val))
		}
		for k, v := range name.KwArgs {
			vals = append(vals, fmt.Sprintf("%v %v", k, v.Val))
		}
		return strings.Join(vals, " "), nil
	},
}); e != nil {
	fmt.Println(e.Error())
	fmt.Println(errors.Unwrap(e))
} else {
	fmt.Println(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant