templatehelper

package module
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 20, 2024 License: MIT Imports: 6 Imported by: 0

README

templatehelper

A Go Library provides helper functions for template package.

Installation

go get -u github.com/northbright/templatehelper

Documentation

Usage

Parse All Template Files in a Directory Recursively

Use ParseDir to parse all files in a directory.

It returns a template.Template slice and each template name is the relative path(with "dir" argument as prefix") of the template file. So the slice may contains multiple templates with same base file names. e.g. "dir/foo.tmpl", "dir/a/foo.tmpl".

package main

import (
        "fmt"

        "github.com/northbright/templatehelper"
)

func main() {
        dir := "templates/markdown"
        tmpls, err := templatehelper.ParseDir(dir, ".md")
        if err != nil {
                fmt.Printf("ParseDir() error: %v\n", err)
        }

        // List the parsed temlates.
        fmt.Printf("Parsed templates:\n")
        for _, tmpl := range tmpls {
                fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
        }

        // Output:
        //Parsed templates:
        //templates>markdown>chapters>00-about.md
        //templates>markdown>chapters>01-installation.md
        //templates>markdown>chapters>02-usage.md
        //templates>markdown>title.md
}

Security

templatehelper uses text/template but not html/template to make it possible to output raw HTML / JS / CSS code.

To secure HTML output, you may need to sanitize the input before execute the templates(e.g. using bluemonday).

Documentation

Index

Examples

Constants

View Source
const (
	DefTmplExt = ".tmpl"
)

Variables

This section is empty.

Functions

func ParseDir

func ParseDir(dir, ext string) ([]*template.Template, error)

ParseDir parses all template files in the given dir and subdirs recursively. It returns a slice contains parsed templates. The name of each parsed template is set to the relative path of the template file. The path contains the "dir" argument as a prefix. dir: the dir contains template files. ext: extend name of template file(e.g. ".tmpl"). It'll use ".tmpl" as default extend name if ext is empty.

Example
package main

import (
	"embed"
	"fmt"
	"log"
	"os"
	"strings"

	_ "embed"
	"github.com/northbright/templatehelper"
)

// Manual represents the manual of templatehelper.
type Manual struct {
	Title        string
	Author       string
	About        string
	Installation string
	ExampleCode  string
}

var manual = Manual{
	Title:        "templatehelper Manual",
	Author:       "Frank Xu",
	About:        "A Go Library provides helper functions for template package.",
	Installation: `go get -u github.com/northbright/templatehelper`,
	ExampleCode:  exampleCode,
}

func main() {
	dir := "templates/markdown"
	tmpls, err := templatehelper.ParseDir(dir, ".md")
	if err != nil {
		log.Printf("ParseDir() error: %v", err)
	}

	if len(tmpls) == 0 {
		log.Printf("No template parsed")
		return
	}

	// List the parsed temlates.
	fmt.Printf("Parsed templates:\n")
	for _, tmpl := range tmpls {
		fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
	}

	// Execute the templates.
	for _, tmpl := range tmpls {
		log.Printf("execute template: %v\n", tmpl.Name())
		tmpl.Execute(os.Stderr, manual)
	}

}

var exampleCode = `
package main

import (
        "fmt"

        "github.com/northbright/templatehelper"
)

func main() {
        dir := "templates/markdown"
        tmpls, err := templatehelper.ParseDir(dir, ".md")
        if err != nil {
                fmt.Printf("ParseDir() error: %v\n", err)
        }

        // List the parsed temlates.
        fmt.Printf("Parsed templates:\n")
        for _, tmpl := range tmpls {
                fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
        }

        // Output:
        //Parsed templates:
        //templates>markdown>chapters>00-about.md
        //templates>markdown>chapters>01-installation.md
        //templates>markdown>chapters>02-usage.md
        //templates>markdown>title.md
}
`
Output:

Parsed templates:
templates>markdown>chapters>00-about.md
templates>markdown>chapters>01-installation.md
templates>markdown>chapters>02-usage.md
templates>markdown>title.md

func ParseDirWithDelims

func ParseDirWithDelims(dir, ext, leftDelim, rightDelim string) ([]*template.Template, error)

ParseDirWithDelims parses all template files in the given dir and subdirs recursively. It returns a slice contains parsed templates. The name of each parsed template is set to the relative path of the template file. The path contains the "dir" argument as a prefix. dir: the dir contains template files. ext: extend name of template file(e.g. ".tmpl"). It'll use ".tmpl" as default extend name if ext is empty. leftDelim / rightDelim: left / right delimiter of the template. It'll use default delimiters("{{" and "}}") of Golang if any of them is empty.

Example
package main

import (
	"embed"
	"fmt"
	"log"
	"os"
	"strings"

	_ "embed"
	"github.com/northbright/templatehelper"
)

// Manual represents the manual of templatehelper.
type Manual struct {
	Title        string
	Author       string
	About        string
	Installation string
	ExampleCode  string
}

var manual = Manual{
	Title:        "templatehelper Manual",
	Author:       "Frank Xu",
	About:        "A Go Library provides helper functions for template package.",
	Installation: `go get -u github.com/northbright/templatehelper`,
	ExampleCode:  exampleCode,
}

func main() {
	// Create and parse templates from .tex file.
	// LaTex uses "{}" for command parameter syntax,
	// which conflicts with default golang template delimiters("{{" and "}}")
	// To use Golang template package to parse .tex file,
	// we use new delimiters: "\{\{" and "\}\}" in the .tex template file.

	dir := "templates/latex"
	tmpls, err := templatehelper.ParseDirWithDelims(dir, ".tex", "\\{\\{", "\\}\\}")
	if err != nil {
		log.Printf("ParseDirWithDelims() error: %v", err)
		return
	}

	if len(tmpls) == 0 {
		log.Printf("No template parsed")
		return
	}

	// List the parsed temlates.
	fmt.Printf("Parsed templates:\n")
	for _, tmpl := range tmpls {
		fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
	}

	// Execute the templates.
	for _, tmpl := range tmpls {
		log.Printf("execute template: %v\n", tmpl.Name())
		tmpl.Execute(os.Stderr, manual)
	}

}

var exampleCode = `
package main

import (
        "fmt"

        "github.com/northbright/templatehelper"
)

func main() {
        dir := "templates/markdown"
        tmpls, err := templatehelper.ParseDir(dir, ".md")
        if err != nil {
                fmt.Printf("ParseDir() error: %v\n", err)
        }

        // List the parsed temlates.
        fmt.Printf("Parsed templates:\n")
        for _, tmpl := range tmpls {
                fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
        }

        // Output:
        //Parsed templates:
        //templates>markdown>chapters>00-about.md
        //templates>markdown>chapters>01-installation.md
        //templates>markdown>chapters>02-usage.md
        //templates>markdown>title.md
}
`
Output:

Parsed templates:
templates>latex>chapters>00-about.tex
templates>latex>chapters>01-installation.tex
templates>latex>chapters>02-usage.tex
templates>latex>manual.tex
templates>latex>title.tex

func ParseFSDir added in v0.1.5

func ParseFSDir(fsys fs.FS, dir, ext string) ([]*template.Template, error)

ParseFSDir parses all template files in the file system and named dir recursively. It returns a slice contains parsed templates. The name of each parsed template is set to the relative path of the template file. The path contains the "dir" argument as a prefix. fsys: file system. dir: the dir contains template files. ext: extend name of template file(e.g. ".tmpl"). It'll use ".tmpl" as default extend name if ext is empty.

Example
package main

import (
	"embed"
	"fmt"
	"log"
	"os"

	_ "embed"
	"github.com/northbright/templatehelper"
)

// Manual represents the manual of templatehelper.
type Manual struct {
	Title        string
	Author       string
	About        string
	Installation string
	ExampleCode  string
}

var (
	manual = Manual{
		Title:        "templatehelper Manual",
		Author:       "Frank Xu",
		About:        "A Go Library provides helper functions for template package.",
		Installation: `go get -u github.com/northbright/templatehelper`,
		ExampleCode:  exampleCode,
	}

	embededTmpls embed.FS
)

func main() {
	dir := "templates/markdown"
	tmpls, err := templatehelper.ParseFSDir(embededTmpls, dir, ".md")
	if err != nil {
		log.Printf("ParseFSDir() error: %v", err)
	}

	if len(tmpls) == 0 {
		log.Printf("No template parsed")
		return
	}

	// List the parsed temlates.
	fmt.Printf("Parsed templates:\n")
	for _, tmpl := range tmpls {
		fmt.Printf("%v\n", tmpl.Name())
	}

	// Execute the templates.
	for _, tmpl := range tmpls {
		log.Printf("execute template: %v\n", tmpl.Name())
		tmpl.Execute(os.Stderr, manual)
	}

}

var exampleCode = `
package main

import (
        "fmt"

        "github.com/northbright/templatehelper"
)

func main() {
        dir := "templates/markdown"
        tmpls, err := templatehelper.ParseDir(dir, ".md")
        if err != nil {
                fmt.Printf("ParseDir() error: %v\n", err)
        }

        // List the parsed temlates.
        fmt.Printf("Parsed templates:\n")
        for _, tmpl := range tmpls {
                fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
        }

        // Output:
        //Parsed templates:
        //templates>markdown>chapters>00-about.md
        //templates>markdown>chapters>01-installation.md
        //templates>markdown>chapters>02-usage.md
        //templates>markdown>title.md
}
`
Output:

Parsed templates:
templates/markdown/chapters/00-about.md
templates/markdown/chapters/01-installation.md
templates/markdown/chapters/02-usage.md
templates/markdown/title.md

func ParseFSDirWithDelims added in v0.1.5

func ParseFSDirWithDelims(fsys fs.FS, dir, ext, leftDelim, rightDelim string) ([]*template.Template, error)

ParseFSDirWithDelims parses all template files in the FS and named dir recursively. It returns a slice contains parsed templates. The name of each parsed template is set to the relative path of the template file. The path contains the "dir" argument as a prefix. fsys: file system. dir: the dir contains template files. ext: extend name of template file(e.g. ".tmpl"). It'll use ".tmpl" as default extend name if ext is empty. leftDelim / rightDelim: left / right delimiter of the template. It'll use default delimiters("{{" and "}}") of Golang if any of them is empty.

Example
package main

import (
	"embed"
	"fmt"
	"log"
	"os"

	_ "embed"
	"github.com/northbright/templatehelper"
)

// Manual represents the manual of templatehelper.
type Manual struct {
	Title        string
	Author       string
	About        string
	Installation string
	ExampleCode  string
}

var (
	manual = Manual{
		Title:        "templatehelper Manual",
		Author:       "Frank Xu",
		About:        "A Go Library provides helper functions for template package.",
		Installation: `go get -u github.com/northbright/templatehelper`,
		ExampleCode:  exampleCode,
	}

	embededTmpls embed.FS
)

func main() {
	// Create and parse templates from .tex file.
	// LaTex uses "{}" for command parameter syntax,
	// which conflicts with default golang template delimiters("{{" and "}}")
	// To use Golang template package to parse .tex file,
	// we use new delimiters: "\{\{" and "\}\}" in the .tex template file.

	dir := "templates/latex"
	tmpls, err := templatehelper.ParseFSDirWithDelims(embededTmpls, dir, ".tex", "\\{\\{", "\\}\\}")
	if err != nil {
		log.Printf("ParseFSDirWithDelims() error: %v", err)
		return
	}

	if len(tmpls) == 0 {
		log.Printf("No template parsed")
		return
	}

	// List the parsed temlates.
	fmt.Printf("Parsed templates:\n")
	for _, tmpl := range tmpls {
		fmt.Printf("%v\n", tmpl.Name())
	}

	// Execute the templates.
	for _, tmpl := range tmpls {
		log.Printf("execute template: %v\n", tmpl.Name())
		tmpl.Execute(os.Stderr, manual)
	}

}

var exampleCode = `
package main

import (
        "fmt"

        "github.com/northbright/templatehelper"
)

func main() {
        dir := "templates/markdown"
        tmpls, err := templatehelper.ParseDir(dir, ".md")
        if err != nil {
                fmt.Printf("ParseDir() error: %v\n", err)
        }

        // List the parsed temlates.
        fmt.Printf("Parsed templates:\n")
        for _, tmpl := range tmpls {
                fmt.Printf("%v\n", strings.ReplaceAll(tmpl.Name(), string(os.PathSeparator), ">"))
        }

        // Output:
        //Parsed templates:
        //templates>markdown>chapters>00-about.md
        //templates>markdown>chapters>01-installation.md
        //templates>markdown>chapters>02-usage.md
        //templates>markdown>title.md
}
`
Output:

Parsed templates:
templates/latex/chapters/00-about.tex
templates/latex/chapters/01-installation.tex
templates/latex/chapters/02-usage.tex
templates/latex/manual.tex
templates/latex/title.tex

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL