Share your custom function (FuncMap) in golang-template

Indroduction

I’m a newbie to Golang.

I like the Golang templates. Especially Template.Funcs makes the templates very powerful.

Unfortunately, it seems that the official Func is too few.

Maybe due to performance or not wanting too many bundles? I wish the template can use Golang syntax as much as possible.

In Hugo, It implemented a lot of functions that I found very useful, but unfortunately, I am not very smart, and I think this project is not suitable for newcomers to learn at the moment (of course, you can also start from the old commit, but it is very tough.) (Don’t worry, as long as your project is related, you are welcome to share it regardless of the difficulty🙂)

Once you are a gopher, I firmly believe that more or less have good Funcs that belong to you created.


What the hell am I going to do?

I create this post in hopes that people will share Funcs so that we can all benefit.

I understand that excellent Funcs should take into account many extreme examples. Still, I think that is not the most important thing, you do not need to worry about criticism because of the not pursuit of perfection, and any sharing is worth it, you can:

  • :writing_hand:Write some code directly here
  • :link: Share links (blog, issues, article, GitHub project, etc.)
  • :muscle: Suggest or improve other people’s code
  • :mage: Explain the code
  • :pray: Ask about your desired function and how to implement it.

Thank you in advance to everyone who responded, and I would like to pay my highest respects for your dedication.:slightly_smiling_face:

Hugo dict

If you are interested in the implementation of Hugo’s dict, these links may be useful to you

unperfect dict

I create a simple dict for reference.

func Dict(values ...interface{}) (map[string]interface{}, error) {
	if len(values)%2 != 0 {
		return nil, errors.New("parameters must be even")
	}
	dict := make(map[string]interface{})
	var key, val interface{}
	for {
		key, val, values = values[0], values[1], values[2:]
		switch reflect.ValueOf(key).Kind() {
		case reflect.String:
			dict[key.(string)] = val
		default:
			return nil, errors.New(`type must equal to "string"`)
		}
		if len(values) == 0 {
			break
		}
	}
	return dict, nil
}

usage

txt

{{- range $key, $val := (dict "User" "Carson" "Msg" "Test") -}}
{{$key}}: {{$val}}
{{ end -}}

{{ $myDict := dict "Msg" "Hello World" }}
{{$myDict.Msg}}

Go Playground