exec.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Jet is a fast and dynamic template engine for the Go programming language, set of features
  15. // includes very fast template execution, a dynamic and flexible language, template inheritance, low number of allocations,
  16. // special interfaces to allow even further optimizations.
  17. package jet
  18. import (
  19. "io"
  20. "reflect"
  21. "sort"
  22. )
  23. type VarMap map[string]reflect.Value
  24. // SortedKeys returns a sorted slice of VarMap keys
  25. func (scope VarMap) SortedKeys() []string {
  26. keys := make([]string, 0, len(scope))
  27. for k := range scope {
  28. keys = append(keys, k)
  29. }
  30. sort.Strings(keys)
  31. return keys
  32. }
  33. func (scope VarMap) Set(name string, v interface{}) VarMap {
  34. scope[name] = reflect.ValueOf(v)
  35. return scope
  36. }
  37. func (scope VarMap) SetFunc(name string, v Func) VarMap {
  38. scope[name] = reflect.ValueOf(v)
  39. return scope
  40. }
  41. func (scope VarMap) SetWriter(name string, v SafeWriter) VarMap {
  42. scope[name] = reflect.ValueOf(v)
  43. return scope
  44. }
  45. // Execute executes the template into w.
  46. func (t *Template) Execute(w io.Writer, variables VarMap, data interface{}) (err error) {
  47. st := pool_State.Get().(*Runtime)
  48. defer st.recover(&err)
  49. st.blocks = t.processedBlocks
  50. st.variables = variables
  51. st.set = t.set
  52. st.Writer = w
  53. // resolve extended template
  54. for t.extends != nil {
  55. t = t.extends
  56. }
  57. if data != nil {
  58. st.context = reflect.ValueOf(data)
  59. }
  60. st.executeList(t.Root)
  61. return
  62. }