AddFunc should adds a global function to the jet template set.
(funcName string, funcBody interface{})
| 132 | |
| 133 | // AddFunc should adds a global function to the jet template set. |
| 134 | func (s *JetEngine) AddFunc(funcName string, funcBody interface{}) { |
| 135 | // if something like "urlpath" is registered. |
| 136 | if generalFunc, ok := funcBody.(func(string, ...interface{}) string); ok { |
| 137 | // jet, unlike others does not accept a func(string, ...interface{}) string, |
| 138 | // instead it wants: |
| 139 | // func(JetArguments) reflect.Value. |
| 140 | |
| 141 | s.AddVar(funcName, jet.Func(func(args JetArguments) reflect.Value { |
| 142 | n := args.NumOfArguments() |
| 143 | if n == 0 { // no input, don't execute the function, panic instead. |
| 144 | panic(funcName + " expects one or more input arguments") |
| 145 | } |
| 146 | |
| 147 | firstInput := args.Get(0).String() |
| 148 | |
| 149 | if n == 1 { // if only the first argument is given. |
| 150 | return reflect.ValueOf(generalFunc(firstInput)) |
| 151 | } |
| 152 | |
| 153 | // if has variadic. |
| 154 | |
| 155 | variadicN := n - 1 |
| 156 | variadicInputs := make([]interface{}, variadicN) // except the first one. |
| 157 | |
| 158 | for i := 0; i < variadicN; i++ { |
| 159 | variadicInputs[i] = args.Get(i + 1).Interface() |
| 160 | } |
| 161 | |
| 162 | return reflect.ValueOf(generalFunc(firstInput, variadicInputs...)) |
| 163 | })) |
| 164 | |
| 165 | return |
| 166 | } |
| 167 | |
| 168 | if jetFunc, ok := funcBody.(jet.Func); !ok { |
| 169 | alternativeJetFunc, ok := funcBody.(func(JetArguments) reflect.Value) |
| 170 | if !ok { |
| 171 | panic(fmt.Sprintf("JetEngine.AddFunc: funcBody argument is not a type of func(JetArguments) reflect.Value. Got %T instead", funcBody)) |
| 172 | } |
| 173 | |
| 174 | s.AddVar(funcName, jet.Func(alternativeJetFunc)) |
| 175 | } else { |
| 176 | s.AddVar(funcName, jetFunc) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // AddVar adds a global variable to the jet template set. |
| 181 | func (s *JetEngine) AddVar(key string, value interface{}) { |