template.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "io/ioutil"
  7. "path/filepath"
  8. )
  9. /*
  10. Parse parses the template definition string to construct a representation of the template for execution.
  11. Trivial usage:
  12. package main
  13. import (
  14. "fmt"
  15. "github.com/Joker/jade"
  16. )
  17. func main() {
  18. tpl, err := jade.Parse("tpl_name", "doctype 5: html: body: p Hello world!")
  19. if err != nil {
  20. fmt.Printf("Parse error: %v", err)
  21. return
  22. }
  23. fmt.Printf( "Output:\n\n%s", tpl )
  24. }
  25. Output:
  26. <!DOCTYPE html><html><body><p>Hello world!</p></body></html>
  27. */
  28. func Parse(name, text string) (string, error) {
  29. outTpl, err := New(name).Parse(text)
  30. if err != nil {
  31. return "", err
  32. }
  33. b := new(bytes.Buffer)
  34. outTpl.WriteIn(b)
  35. return b.String(), nil
  36. }
  37. // ParseFile parse the jade template file in given filename
  38. func ParseFile(filename string) (string, error) {
  39. bs, err := ioutil.ReadFile(filename)
  40. if err != nil {
  41. return "", err
  42. }
  43. return Parse(filepath.Base(filename), string(bs))
  44. }
  45. func (t *Tree) WriteIn(b io.Writer) {
  46. t.Root.WriteIn(b)
  47. }