Common isomorphic functionality in one kit.

templatebundle.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // The Isomorphic Go Project
  2. // Copyright (c) Wirecog, LLC. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license, which can be found in the LICENSE file.
  5. package isokit
  6. import (
  7. "io/ioutil"
  8. "log"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. )
  13. type TemplateBundle struct {
  14. items map[string]string
  15. }
  16. func NewTemplateBundle() *TemplateBundle {
  17. return &TemplateBundle{
  18. items: map[string]string{},
  19. // Funcs: template.FuncMap{},
  20. }
  21. }
  22. func (t *TemplateBundle) Items() map[string]string {
  23. return t.items
  24. }
  25. func (t *TemplateBundle) importTemplateFileContents(templatesPath string) error {
  26. templateDirectory := filepath.Clean(templatesPath)
  27. if err := filepath.Walk(templateDirectory, func(path string, info os.FileInfo, err error) error {
  28. if strings.HasSuffix(path, TemplateFileExtension) {
  29. name := strings.TrimSuffix(strings.TrimPrefix(path, templateDirectory+string(os.PathSeparator)), TemplateFileExtension)
  30. contents, err := ioutil.ReadFile(path)
  31. t.items[name] = string(contents)
  32. if err != nil {
  33. log.Println("error encountered while walking directory: ", err)
  34. return err
  35. }
  36. }
  37. return nil
  38. }); err != nil {
  39. return err
  40. }
  41. return nil
  42. }
  43. func (t *TemplateBundle) importTemplateFileContentsForCog(templatesPath string, prefixName string, templateFileExtension string) error {
  44. templateDirectory := filepath.Clean(templatesPath)
  45. RegisterStaticAssetsSearchPath(strings.Replace(templateDirectory, "/templates", "", -1))
  46. //println("td: ", templateDirectory)
  47. if err := filepath.Walk(templateDirectory, func(path string, info os.FileInfo, err error) error {
  48. if strings.HasSuffix(path, templateFileExtension) {
  49. name := strings.TrimSuffix(strings.TrimPrefix(path, templateDirectory+string(os.PathSeparator)), TemplateFileExtension)
  50. name = prefixName + "/" + name
  51. contents, err := ioutil.ReadFile(path)
  52. t.items[name] = string(contents)
  53. if err != nil {
  54. log.Println("error encountered while walking directory: ", err)
  55. return err
  56. }
  57. }
  58. return nil
  59. }); err != nil {
  60. return err
  61. }
  62. return nil
  63. }