A tool to be used with 'go generate' to embed external template files into Go code.

templify

A tool to be used with 'go generate' to embed external template files into Go code.

Scenario

An often used scenario in developing go applications is to generate text (e.g. html pages) using the Go template packages. You have two choices: either editing the template in a dedicated file and to read this file at runtime from your application. Or you add a "big" string containing the template to the source of your app and parse this string to create the template.

If you want to create a single file application, then the more handy solution with a dedicated file is not desirable. On the other hand to edit a complex html template within a Go string in the source is very uncomfortable.

templify allows you to edit your template in an extra file and to generate an Go source file containing the embedded string.

Installation

go get github.com/wlbr/templify

Usage

Simply add a line

//go:generate templify mytemplate.file

for each template you want to embed. Every time you run a go generate in the corresponding folder, the file mytemplate.go will be created. It contains a function mytemplateTemplate returning the template string.

You may use templify mytemplate.file directly on the command line.

Switches

Usage of templify: templify [switches] templatefilename
-e
   export the generated, the template returning function. Default (false) means the function will not be exported.

-f
   no formatting of the generated source. Default false means source will be formatted with gofmt.

-n string
    name of generated, the template returning function. Its name will have 'Template' attached. Will be set to $(basename -s .ext outputfile) if empty (default).

-o string
   name of output file. Defaults to name of template file excluding extension + '.go'.

-p string
   name of package to be used in generated code (default "main").

-t string
   name of alternate code generation template file. If empty (default), then the embedded template will be used. Template variables supplied are: .Name, .Package, .Content

Code

Owner
Michael Wolber
Nützt ja nix.
Michael Wolber
Similar Resources

a better customizable tool to embed files in go; also update embedded files remotely without restarting the server

fileb0x What is fileb0x? A better customizable tool to embed files in go. It is an alternative to go-bindata that have better features and organized c

Dec 27, 2022

The simple and easy way to embed static files into Go binaries.

NOTICE: Please consider migrating your projects to github.com/markbates/pkger. It has an idiomatic API, minimal dependencies, a stronger test suite (t

Dec 25, 2022

Embed files into a Go executable

statik statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem. Is this a crazy idea? No

Dec 29, 2022

Embed files into a Go executable

statik statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem. Is this a crazy idea? No

Jan 6, 2023

Ghostinthepdf - This is a small tool that helps to embed a PostScript file into a PDF

This is a small tool that helps to embed a PostScript file into a PDF in a way that GhostScript will run the PostScript code during the

Dec 20, 2022

Embed arbitrary resources into a go executable at runtime, after the executable has been built.

ember Ember is a lightweight library and tool for embedding arbitrary resources into a go executable at runtime. The resources don't need to exist at

Nov 9, 2022

This command line converts .html file into .html with images embed.

embed-html This command line converts .html file into .html with images embed. Install go get github.com/gonejack/embed-html Usage embed-html *.ht

Oct 6, 2022

Using brotli compression to embed static files in Go.

Using brotli compression to embed static files in Go.

🥦 Broccoli go get -u aletheia.icu/broccoli Broccoli uses brotli compression to embed a virtual file system of static files inside Go executables. A f

Nov 25, 2022

Embed static files in Go binaries (replacement for gobuffalo/packr)

Pkger github.com/markbates/pkger is a tool for embedding static files into Go binaries. It will, hopefully, be a replacement for github.com/gobuffalo/

Dec 29, 2022

erchive is a go program that compresses and encrypts files and entire directories into .zep files (encrypted zip files).

erchive/zep erchive is a go program that compresses and encrypts files and entire directories into .zep files (encrypted zip files). it compresses usi

May 16, 2022

A reverse-proxy cache for external images used on LinuxFr.org

External images on LinuxFr.org Our users can use images from external domains on LinuxFr.org. This component is a reverse-proxy / cache for these imag

May 14, 2021

MNA - stands for mobile number assignment - a small zero external dependency golang library that is used to identify mobile number assignment in tanzania

MNA - stands for mobile number assignment - a small zero external dependency golang library that is used to identify mobile number assignment in tanzania

Nov 29, 2021

A command line tool that builds and (re)starts your web application everytime you save a Go or template fileA command line tool that builds and (re)starts your web application everytime you save a Go or template file

# Fresh Fresh is a command line tool that builds and (re)starts your web application everytime you save a Go or template file. If the web framework yo

Nov 22, 2021

:zap: boilerplate template manager that generates files or directories from template repositories

:zap: boilerplate template manager that generates files or directories from template repositories

Boilr Are you doing the same steps over and over again every time you start a new programming project? Boilr is here to help you create projects from

Jan 6, 2023

Utility CLI to convert Spring Boot Yaml configuration into external configuration

boot-config-export Utility CLI to convert Spring Boot Yaml configuration into external configuration (as environment variables). The variables are tra

Nov 17, 2021

Simple system for writing HTML/XML as Go code. Better-performing replacement for html/template and text/template

Simple system for writing HTML as Go code. Use normal Go conditionals, loops and functions. Benefit from typing and code analysis. Better performance than templating. Tiny and dependency-free.

Dec 5, 2022

tinygo-used-files is a CLI tool that lists only the files to be built as specified by buildtag.

tinygo-used-files is a CLI tool that lists only the files to be built as specified by buildtag.

Feb 6, 2022
Comments
  • i have a upgrade for you

    i have a upgrade for you

    //go build -o %gopath%/bin/templify.exe github.com\wlbr\templify // templify is a tool to be used with 'go generate' to embed external template files into Go code. // // // Scenario // // An often used scenario in developing go applications is to generate text (e.g. html pages) // using the Go template packages. You have two choices: either editing the template in a // dedicated file and to read this file at runtime from your application. Or you add a // "big" string containing the template to the source of your app and parse this string to // create the template. // // If you want to create a single file application, than the more handy solution with a // dedicated file is not desirable. On the other hand to edit a complex html template within // a Go string in the source is very uncomfortable. // // templify allows you to edit your template in an extra file and to generate an Go source // file containing the embedded string. // // // Usage // // Simply add a line // //go:generate templify mytemplate.file // // for each template you want to embed. Every time you run a 'go generate' in the // corresponding folder, the file 'mytemplate.go' will be created. It contains a // function 'mytemplateTemplate' returning the template string. // // You may use 'templify mytemplate.file' directly on the command line. // // // Switches // // Usage of templify: 'templify [switches] templatefilename' // -e // export the generated, the template returning function. Default (false) means // the function will not be exported. // -f // no formatting of the generated source. Default false means source will be // formatted with gofmt. // // -n string // name of generated, the template returning function. Its name will have // 'Template' attached. Will be set to $(basename -s .ext outputfile) if empty // (default). // // -o string // name of output file. Defaults to name of template file excluding // extension + '.go'. // // -p string // name of package to be used in generated code (default "main"). // // -t string // name of alternate code generation template file. If empty (default), then // the embedded template will be used. Template variables supplied are: // .Name, .Package, .Content // package main

    //go:generate templify -p main -o embed.go embed.tpl

    import ( "errors" "flag" "fmt" "go/format" "io/ioutil" "os" "path" "strings" "text/template" )

    var pckg string var inputfile string var outfilename string var functionname string var tmplname string var frmt bool var exp bool

    func flagging() { flag.StringVar(&pckg, "p", "main", "name of package to be used in generated code.") flag.StringVar(&outfilename, "o", "", "name of output file. Defaults to name of template file + '.go'.") flag.StringVar(&functionname, "f", "", "name of generated, the template returning function. Its name will "+ "have 'Template' attached. Will be set to $(basename -s .ext outputfile) if empty (default).") flag.StringVar(&tmplname, "t", "", "name of alternate code generation template file. If empty (default), "+ "then the embedded template will be used. Template variables supplied are: .Name, .Package, .Content") flag.BoolVar(&frmt, "n", false, "do not format the generated source. Default false means source will be formatted.") flag.BoolVar(&exp, "e", false, "export the generated, the template returning function. "+ "Default (false) means the function will not be exported.") flag.Parse()

    if outfilename == "" {
    	indir := path.Dir(inputfile)
    	inext := path.Ext(path.Base(inputfile))
    	inname := strings.TrimSuffix(path.Base(inputfile), inext)
    	outfilename = fmt.Sprintf("%s/%s.go", indir, inname)
    }
    
    if functionname == "" {
    	ext := path.Ext(path.Base(outfilename))
    	functionname = strings.TrimSuffix(path.Base(outfilename), ext)
    }
    
    if exp {
    	functionname = strings.ToUpper(functionname[0:1]) + functionname[1:]
    }
    

    }

    func readTemplifyTemplate(tplname string) (*template.Template, error) { tpl, err := template.ParseFiles(tplname) if err != nil { fmt.Printf("Error reading templifytemplate file '%s'\n%v", tplname, err) } return tpl, err }

    func readTargetTemplate2(tplname string) string { tpl, err := ioutil.ReadFile(tplname) if err != nil { fmt.Printf("Error reading target template file '%s'\n%v", tplname, err) os.Exit(1) }

    r := strings.NewReplacer("\"", "\\\"", "\n", "\\n\" +\n\t\"", "\t", "\\t")
    return r.Replace(string(tpl))
    

    } func readTargetTemplate(tplname string) string { tpl, err := ioutil.ReadFile(tplname) if err != nil { fmt.Printf("Error reading target template file '%s'\n%v", tplname, err) os.Exit(1) }

    //r := strings.NewReplacer("\"", "\\\"", "\n", "\\n\" +\n\t\"", "\t", "\\t")
    return string(tpl)
    

    } func formatFile(fname string) { fstr, err := ioutil.ReadFile(fname) if err != nil { fmt.Printf("Error reading generated file %s before passing it to gofmt.\n%v\n", fname, err) os.Exit(1) } else { fstr, err = format.Source(fstr) if err != nil { fmt.Printf("Error running gofmt on the generated file '%s'\n%v\n", fname, err) os.Exit(1) } else { foutfile, err := os.Create(fname) if err != nil { fmt.Printf("Error creating formatted target file '%s'\n%v\n", fname, err) os.Exit(1) } else { defer foutfile.Close() fmt.Fprintf(foutfile, "%s", fstr) } } } }

    func main() { flagging()

    inputfile = flag.Arg(0)
    if inputfile == "" {
    	fmt.Println(errors.New("No template file given as argument."))
    	os.Exit(1)
    }
    
    var tpl *template.Template
    var err error
    
    if tmplname != "" {
    	tpl, err = readTemplifyTemplate(tmplname)
    
    } else {
    	tpl, err = template.New("embed").Parse(embedTemplate())
    }
    
    //tpl, err := template.New("embed").Parse(internalTemplate)
    
    if err != nil {
    	fmt.Printf("Error parsing code generation template\n%v", err)
    	os.Exit(1)
    }
    
    data := struct {
    	Package string
    	Name    string
    	Content string
    }{
    	Package: pckg,
    	Name:    strings.Split(functionname, ".")[0],
    }
    data.Content =   readTargetTemplate(inputfile) 
    
    if outfilename == "" {
    	outfilename = strings.Split(inputfile, ".")[0] + ".go"
    }
    outfile, err := os.Create(outfilename)
    if err != nil {
    	fmt.Printf("Error creating target file '%s'\n%v\n", outfilename, err)
    	os.Exit(1)
    }
    defer outfile.Close()
    tpl.Execute(outfile, data)
    
    if !frmt {
    	formatFile(outfilename)
    }
    

    }

  • Possible to pack SQLite file?

    Possible to pack SQLite file?

    I have a program that read data from local sqlite db, and show data to users, I wanna to pack all assets include sqlite file to one binary file, this program only execute read operation from sqlite, is it possible to pack sqlite file?

  • invalid default output filename

    invalid default output filename

    when an output file name is not specified with the -o flag, a file called ".go" is generated in the current folder, instead of using the basename of the input file

  • Support templify-ing all files in a folder

    Support templify-ing all files in a folder

    This is very useful if there is a folder with multiple template files, they could maybe templified to a file with the give package name or with the name of the folder as the package.

    What do you think?

a better customizable tool to embed files in go; also update embedded files remotely without restarting the server

fileb0x What is fileb0x? A better customizable tool to embed files in go. It is an alternative to go-bindata that have better features and organized c

Dec 27, 2022
The simple and easy way to embed static files into Go binaries.

NOTICE: Please consider migrating your projects to github.com/markbates/pkger. It has an idiomatic API, minimal dependencies, a stronger test suite (t

Dec 25, 2022
Embed files into a Go executable

statik statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem. Is this a crazy idea? No

Dec 29, 2022
Using brotli compression to embed static files in Go.
Using brotli compression to embed static files in Go.

?? Broccoli go get -u aletheia.icu/broccoli Broccoli uses brotli compression to embed a virtual file system of static files inside Go executables. A f

Nov 25, 2022
:file_folder: Embeds static resources into go files for single binary compilation + works with http.FileSystem + symlinks

Package statics Package statics embeds static files into your go applications. It provides helper methods and objects to retrieve embeded files and se

Sep 27, 2022
Takes an input http.FileSystem (likely at go generate time) and generates Go code that statically implements it.

vfsgen Package vfsgen takes an http.FileSystem (likely at go generate time) and generates Go code that statically implements the provided http.FileSys

Dec 18, 2022
Get an embed.FS from inside an embed.FS
Get an embed.FS from inside an embed.FS

embed.FS wrapper providing additional functionality Features Get an embed.FS from an embedded subdirectory Handy Copy(sourcePath, targetPath) method t

Sep 27, 2022
Generates go code to embed resource files into your library or executable

Deprecating Notice go is now going to officially support embedding files. The go command will support //go:embed tags. Go Embed Generates go code to e

Jun 2, 2021
Split multiple Kubernetes files into smaller files with ease. Split multi-YAML files into individual files.

Split multiple Kubernetes files into smaller files with ease. Split multi-YAML files into individual files.

Dec 29, 2022
Split multiple Kubernetes files into smaller files with ease. Split multi-YAML files into individual files.

kubectl-slice: split Kubernetes YAMLs into files kubectl-slice is a neat tool that allows you to split a single multi-YAML Kubernetes manifest into mu

Jan 3, 2023