template

package
v0.0.0-...-693abe4 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2019 License: MIT Imports: 5 Imported by: 0

README

Golang Template Travis-CI GoDoc Go Report Card

A template which is used to get a golang value by template string from a context. Instead of parsing template into a bytes stream, it return the golang value directlly.

Installation

go get github.com/cloudfly/template

Example

package main

import (
        "fmt"
        "github.com/cloudfly/template"
)

type Context struct {
	data map[string]interface{}
}

func (c Context) Value(key string) interface{} {
	if d, ok := c.data[key]; ok {
		return d
	}
	return nil
}

func main() {
	ctx := Context{
		data: map[string]interface{}{
                    "b": true,
                },
	}

        result, err := template.Parse("{{ .b }}", ctx)
        if err != nil {
                panic(err)
        }
        // result is not a string or bytes, it's a interface{} of a boolean.
        fmt.Println(result.(bool))
        // print true
}

Contributting

It parse the template by using text/template/parse, and the realization of it also refrences the text/template package.

The template syntax is same with text/template, but only support simple expression that returning a golang value, no range, no if-else, no block.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(s string, data Data) (interface{}, error)

Parse a template string directlly, it is same to call New() and then Execute().

Types

type Data

type Data interface {
	Value(string) interface{}
}

Data represent a data source, which contains the value used in template. template will find value in it.

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template is a object parsed from template-string

func New

func New(s string) (*Template, error)

New create a new template from a string

func (*Template) Execute

func (t *Template) Execute(data Data) (interface{}, error)

Execute return the golang value which the template represented

func (*Template) String

func (t *Template) String() string

String return the original template string

Jump to

Keyboard shortcuts

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