template.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Jade.go - template engine. Package implements Jade-lang templates for generating Go html/template output.
  2. package jade
  3. import (
  4. "bytes"
  5. "io"
  6. "net/http"
  7. )
  8. /*
  9. Parse parses the template definition string to construct a representation of the template for execution.
  10. Trivial usage:
  11. package main
  12. import (
  13. "fmt"
  14. "html/template"
  15. "net/http"
  16. "github.com/Joker/jade"
  17. )
  18. func handler(w http.ResponseWriter, r *http.Request) {
  19. jadeTpl, _ := jade.Parse("jade", []byte("doctype 5\n html: body: p Hello #{.Word}!"))
  20. goTpl, _ := template.New("html").Parse(jadeTpl)
  21. goTpl.Execute(w, struct{ Word string }{"jade"})
  22. }
  23. func main() {
  24. http.HandleFunc("/", handler)
  25. http.ListenAndServe(":8080", nil)
  26. }
  27. Output:
  28. <!DOCTYPE html><html><body><p>Hello jade!</p></body></html>
  29. */
  30. func Parse(fname string, text []byte) (string, error) {
  31. outTpl, err := New(fname).Parse(text)
  32. if err != nil {
  33. return "", err
  34. }
  35. bb := new(bytes.Buffer)
  36. outTpl.WriteIn(bb)
  37. return bb.String(), nil
  38. }
  39. // ParseFile parse the jade template file in given filename
  40. func ParseFile(fname string) (string, error) {
  41. text, err := ReadFunc(fname)
  42. if err != nil {
  43. return "", err
  44. }
  45. return Parse(fname, text)
  46. }
  47. // ParseWithFileSystem parse in context of a http.FileSystem (supports embedded files)
  48. func ParseWithFileSystem(fname string, text []byte, fs http.FileSystem) (str string, err error) {
  49. outTpl := New(fname)
  50. outTpl.fs = fs
  51. outTpl, err = outTpl.Parse(text)
  52. if err != nil {
  53. return "", err
  54. }
  55. bb := new(bytes.Buffer)
  56. outTpl.WriteIn(bb)
  57. return bb.String(), nil
  58. }
  59. // ParseFileFromFileSystem parse template file in context of a http.FileSystem (supports embedded files)
  60. func ParseFileFromFileSystem(fname string, fs http.FileSystem) (str string, err error) {
  61. text, err := readFile(fname, fs)
  62. if err != nil {
  63. return "", err
  64. }
  65. return ParseWithFileSystem(fname, text, fs)
  66. }
  67. func (t *tree) WriteIn(b io.Writer) {
  68. t.Root.WriteIn(b)
  69. }