fet

package module
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: MIT Imports: 21 Imported by: 1

README

FET

tag test codecov

FET is a golang template engine that can tranlate smarty like template code into golang html/template.

Why FET

FET means Friendly, Easily for Template code. The official golang package html/template is a fully functional template engine, but it has a few defects with user experience, so you need FET.

Features
  • Expression logics
  • Use incldue with defined variables scopes
  • Use extends inherit base template with defined variables scopes
  • Limited support for for and capture

Document

Document

中文文档

Usage

it's more likely to the php template engine smarty.

  • inherit

    {%extends "base.html"%}
    
  • blocks for inherit

    {%block "header"%}
      <div>some code here</div>
    {%/block%}
    
  • include

    {%include file="header.html" var=1%}
    
  • loop, do not support keyword break continue

    // for Gofet mode
    {%for item,key in list%}
      // output
    {%/for%}
    
    {%for i = 0, j = 10; i < j; i++%}
      // output
    {%/for%}
    // for Smarty mode
    {%foreach $list as $key => $item%}
      // output
    {%/foreach%}
    // for
    {%for $i = 0, $j = 10; $i < $j; $i++%}
      // output
    {%/for%}
    
  • if condition

    {%if $num > 100%}
    
    {%elseif $num < 50%}
    
    {%else%}
    
    {%/if%}
    
  • output

    {%$item.url%}
    
  • pipe funcs

    {%$item.title|truncate:30%}
    
  • variable define

    {%$title = "this is a title"%}
    
  • capture

    {%capture "hello"%}hello{%/capture%}
    {%if true%}
      {%$fet.capture.hello%},wolrd!
    {%else%}
      just {%$fet.capture.hello%}!
    {%/if%}
    
  • static variables

    {%$fet.capture.xxx%}
    {%$fet.config.leftDelimiter%}
    {%$fet.config.rightDelimiter%}
    {%$fet.config.templateDir%}
    {%$fet.config.compileDir%}
    {%$fet.now%}
    {%$fet.debug%} // will output all the variables that assigned in the template<include variables that difined in the template by yourself> to the js devtools's Console panel.
    
  • special variables

    {%$ROOT%}  // will output $
    {%$fet%} // will output .
    
Expression
  1. operators: You can either use the keyword operator or the punctuation.

    keyword punctuation example
    and && 1 && 2 <=> 1 and 2
    or || 1 || 2 <=> 1 or 2
    not ! !a <=> not a
    eq == a == b <=> a eq b
    ne != a != b <=> a ne b
    gt > a > b <=> a gt b
    ge >= a >= b <=> a ge b
    lt < a < b <=> a lt b
    le <= a <= b <=> a le b
    bitor - a bitor b
    - & a & b
    - ^ a ^ b
    - + a + b
    - - a - b
    - * a * b
    - / a / b
    - % a % b
    - ** a ** b

    Be careful of the and and or operators, they don't have short circuit with conditions.

  2. pipe
    | pipeline funcs
    : set parameters for pipeline funcs

  3. numbers
    hex: 0xffff
    octal: 0o777
    binary: 0b1000
    scientific notation 1e10

String concat
{% $sayHello = "world" %}
{% "hello `$sayHello`"%} // output "hello world"

use `` for variable or expression in strings. do not use +.

Func Maps
  • Math
    min max floor ceil

  • Formats
    number_format

  • Strings truncate concat ucwords

  • Assert
    empty

  • Length
    count

  • Output
    safe

  • view more in funcs.go

Config types.Mode
  • types.Smarty
    the variable and field must begin with $, use foreach tag for loops.
  • types.Gofet
    the variable and field mustn't begin with $, use for tag for loops.
In development
# install command line tool `fetc`
go get -v github.com/fefit/fetc
# then init the config, will make a config file `fet.config.json`
fetc init
# then watch the file change, compile your fet template file immediately
fetc watch
Demo code
package main

import (
  "os"
  "github.com/fefit/fet"
  "github.com/fefit/fet/types"
)

func main(){
  conf := &fet.Config{
    LeftDelimiter: "{%", // default "{%"
    RightDelimiter: "%}", // default "%}"
    TemplateDir: "tmpls", //  default "templates"
    CompileDir: "views", // default "templates_c",
    Ignores: []string{"inc/*"}, // ignore compile,paths and files that will be included and extended. use filepath.Match() method.
    UcaseField: false, // default false, if true will auto uppercase field name to uppercase.
    CompileOnline: false, // default false, you should compile your template files offline
    Glob: false, // default false, if true, will add {{define "xxx"}}{{end}} to wrap the compiled content,"xxx" is the relative pathname base on your templateDir, without the file extname.
    AutoRoot: false, // default false,if true, if the variable is not assign in the scope, will treat it as the root field of template data, otherwise you need use '$ROOT' to index the data field.
    Mode: types.Smarty, // default types.Smarty, also can be "types.Gofet"
  }
  fet, _ := fet.New(conf)
  // assign data
  data := map[string]interface{}{
    "Hello": "World"
  }
  // the index.html {%$ROOT.Hello%}
  // Display
  fet.Display("index.html", data, os.Stdout)
  // will output: World
}

API
static methods
  • fet.LoadConf(configFile string) (*types.FetConfig, error)

    if you use the command line fetc build a config file fet.config.json, then you can use fet.LoadConf to get the config.

  • fet.New(config *types.FetConfig) (instance *Fet, error)

    get a fet instance.

instance methods
  • instance.Compile(tpl string, createFile bool) (result string, err error)

    compile a template file, if createFile is true, will create the compiled file.

  • instance.CompileAll() error

    compile all files need to compile.

  • instance.Display(tpl string, data interface{}, output io.Wirter) error

    render the parsed html code into output.

  • instance.Fetch(tpl string, data interface{}) (result string, err error)

    just get the parsed string code, it always use CompileOnline mode.

Use in project

  1. compile mode

    just use fet compile your template files offline, and add the FuncMap lib/funcs/funcs.go to your project.

  2. install mode

    install fet,and use fet.Display(tpl, data, io.Writer) to render the template file.

License

MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CompileOptions

type CompileOptions struct {
	File          string
	ParentNS      string
	LocalNS       string
	ParentScopes  []string
	LocalScopes   *[]string
	Includes      *[]string
	IncludeChains *Imports
	Extends       *[]string
	Captures      *map[string]string
	ParseOptions  *generator.ParseOptions
}

CompileOptions struct

type Config

type Config = types.FetConfig

Config for FetConfig

func LoadConf

func LoadConf(confFile string) (*Config, error)

LoadConf load the config file

type Data

type Data struct {
	Name  string
	Props Props
}

Data struct

type Fet

type Fet struct {
	*Config
	Params
	CompileDir  string
	TemplateDir string
	// contains filtered or unexported fields
}

Fet struct

func New

func New(config *Config) (fet *Fet, err error)

New create a template enginner

func (*Fet) CheckConfig

func (fet *Fet) CheckConfig() error

*

  • fet.CheckConfig
  • ---------------------------
  • check if a config is ok
  • ---------------------------

func (*Fet) Compile

func (fet *Fet) Compile(tpl string, writeFile bool) (string, []string, error)

*

  • fet.Compile
  • ---------------------------
  • compile one template file
  • ---------------------------

func (*Fet) CompileAll

func (fet *Fet) CompileAll() (*sync.Map, error)

*

  • fet.CompileAll
  • ---------------------------
  • compile all the files
  • ---------------------------

func (*Fet) Display

func (fet *Fet) Display(tpl string, data interface{}, output io.Writer) (err error)

Display method

func (*Fet) Fetch

func (fet *Fet) Fetch(tpl string, data interface{}) (result string, err error)

Fetch method

func (*Fet) GetCompileFiles

func (fet *Fet) GetCompileFiles(dorf string) ([]string, error)

GetCompileFiles get need compiled files

func (*Fet) NeedIgnore

func (fet *Fet) NeedIgnore(dorf string) bool

NeedIgnore check the file or directory should be ignored.

func (*Fet) RealCmplPath

func (fet *Fet) RealCmplPath(tpl string) string

RealCmplPath get the template file path

func (*Fet) RealTmplPath

func (fet *Fet) RealTmplPath(tpl string) string

RealTmplPath get the template file path

func (*Fet) ShortTmplPath added in v0.1.6

func (fet *Fet) ShortTmplPath(tpl string) string

ShortTemplPath

type ImportNode added in v0.1.10

type ImportNode struct {
	Value string
	Prevs []*ImportNode
}

ImportNode every node will lookup it's prevs so nexts are not necessary

func (*ImportNode) LookupCircle added in v0.1.10

func (importNode *ImportNode) LookupCircle(search *ImportNode, chains []*ImportNode) []string

type Imports added in v0.1.10

type Imports struct {
	Nodes map[string]*ImportNode
}

func (*Imports) Add added in v0.1.10

func (imports *Imports) Add(cur string, depend string) []string

type Indexs

type Indexs = types.Indexs

Indexs for tags

type MatchTagFn

type MatchTagFn func(strs *Runes, index int, total int) (int, bool)

MatchTagFn func

type Mode

type Mode = types.Mode

Mode for parser type

type Node

type Node struct {
	IsClosed     bool
	ContentIndex int
	Name         string
	Content      string
	Pwd          string
	GlobalScopes []string
	LocalScopes  []string
	Parent       *Node
	Pair         *Node
	Type         Type
	Props        *Props
	Features     []*Node
	Childs       []*Node
	Current      *Node
	Quotes       []*Quote
	Context      *Runes
	Fet          *Fet
	Data         *map[string][]string
	Indexs
	*Position
}

Node struct

func (*Node) AddFeature

func (node *Node) AddFeature(feature *Node)

AddFeature method for Node

func (*Node) Compile

func (node *Node) Compile(options *CompileOptions) (result string, err error)

Compile method for Node

func (*Node) Validate

func (node *Node) Validate(conf *Config) (errmsg string)

Validate method for Node

type NodeList

type NodeList struct {
	Queues   []*Node
	Specials NodeSets
}

NodeList for

type NodeSets

type NodeSets map[string][]*Node

NodeSets for nodelist

type Params

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

Params struct

type Position

type Position struct {
	LineNo    int
	LineIndex int
}

Position struct

type Prop

type Prop struct {
	Raw  string
	Type string
}

Prop of Props

type Props

type Props map[string]*Prop

Props of tag

type Quote

type Quote struct {
	Indexs
}

Quote struct

type Runes

type Runes []rune

Runes type

type Type

type Type int

Type type

const (
	UnknownType Type = iota
	TextType
	CommentType
	OutputType
	AssignType
	SingleType
	BlockType
	BlockStartType
	BlockFeatureType
	BlockEndType
)

UnknownType need parse

type ValidateFn

type ValidateFn func(node *Node, conf *Config) string

ValidateFn func

Directories

Path Synopsis
lib

Jump to

Keyboard shortcuts

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