github.com/servernoj/jade@v0.0.0-20231225191405-efec98d19db1/template.go (about)

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