templates

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 20, 2023 License: GPL-2.0 Imports: 5 Imported by: 0

README

Rendering templates

Firstly, we need to define a variable variables in the github.com/Nigel2392/templates/response package:

response.TEMPLATE_MANAGER = &templates.Manager{
	// Configure default template settings.
	TplFileSystem:   os.DirFS("templates/"),
	BaseTplSuffixes: []string{".tmpl"},
	BaseTplDirs:     []string{"base"},
	TplDirs:         []string{"templates"},
	UseTplCache:     false,
	DefaultTplFuncs: template.FuncMap{
		"helloworld": func() string {
			return "hello world!"
		},
	},
}
  

As you might see from the above code, this follows your file structure. We do not have to define the regular template directories, but we do have to define the base template directories. We define the regular directories when rendering them.

    # The base directory is where the base templates are stored.
    templates/
    ├── base
    │   └── base.tmpl
    └── app
        ├── index.tmpl
        └── user.tmpl

Then, we can render templates like so:

func indexFunc(w *http.ResponseWriter, r *http.Request) {
    // Render the template with the given data.
    var err = response.Render(w, "app/index.tmpl", map[string]any{"this":"is_custom_tpl_data"})
    if err != nil {
	req.WriteString(err.Error())
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FilenameFromPath

func FilenameFromPath(p string) string

func NicePath

func NicePath(forceSuffixSlash bool, p ...string) string

Types

type Manager

type Manager struct {
	// Use template cache?
	UseTplCache bool

	// Default base template suffixes
	BaseTplSuffixes []string
	// Default directory to look in for base templates
	BaseTplDirs []string
	TplDirs     []string
	// Functions to add to templates
	DefaultTplFuncs template.FuncMap
	// Template file system
	TplFileSystem fs.FS
	// contains filtered or unexported fields
}

Template manager Used for easily fetching templates.

func (*Manager) Get

func (tm *Manager) Get(templateName string) (*template.Template, string, error)

Get a template

func (*Manager) GetBases

func (tm *Manager) GetBases(funcMap template.FuncMap) (*template.Template, error)

Get base templates

func (*Manager) GetFromString

func (tm *Manager) GetFromString(templateString string, templateName string) (*template.Template, error)

Render a template from a string

func (*Manager) Init

func (tm *Manager) Init()

Initialize the template manager

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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