pug

package module
v0.0.0-...-a633e10 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2024 License: MIT Imports: 16 Imported by: 0

README

pug.go - template engine for Go (golang)

Package pug (github.com/shaban/pug) is a simple and fast template engine implementing the pug template engine pug/Pug. It is a fork of github.com/Joker/jade aiming to keep up with go releases and enable usage in wasm environments. Pug precompiles templates to Go code or generates html/template.

GoDoc Go Report Card Go Report Card

pug syntax

example:

//-  :go:func Index(pageTitle string, youAreUsingpug bool)

mixin for(golang)
    #cmd Precompile pug templates to #{golang} code.

doctype html
html(lang="en")
    head
        title= pageTitle
        script(type='text/javascript').
            if(question){
                answer(40 + 2)
            }
    body
        h1 pug - template engine
            +for('Go')

        #container.col
            if youAreUsingpug
                p You are amazing
            else
                p Get on it!
            p.
                pug/Pug is a terse and simple
                templating language with
                a #[strong focus] on performance 
                and powerful features.

becomes

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>pug.go</title>
        <script type="text/javascript">
            if(question){
                answer(40 + 2)
            }
        </script>
    </head>
    <body>
        <h1>pug - template engine
            <div id="cmd">Precompile pug templates to Go code.</div>
        </h1>
        <div id="container" class="col">
            <p>You are amazing</p>
            <p>
                pug/Pug is a terse and simple
                templating language with
                a <strong>focus</strong> on performance 
                and powerful features.
            </p>
        </div>
    </body>
</html>

Here are additional examples and test cases.

Installation

Install pug compiler

go install github.com/shaban/pug/cmd/pug@latest

or github.com/shaban/pug package

go get -u github.com/shaban/pug

Example usage

pug compiler
pug -writer -pkg=main hello.pug

pug command[^1] precompiles hello.pug to hello.pug.go

hello.pug

:go:func(arg) word string
doctype 5
html
    body
        p Hello #{word}!

hello.pug.go

// Code generated by "pug.go"; DO NOT EDIT.
package main

import "io"

const (
    hello__0 = `<!DOCTYPE html><html><body><p>Hello `
    hello__1 = `!</p></body></html>`
)
func pug_hello(word string, wr io.Writer) {
    buffer := &WriterAsBuffer{wr}
    buffer.WriteString(hello__0)
    WriteEscString(word, buffer)
    buffer.WriteString(hello__1)
}

main.go

package main
//go:generate pug -pkg=main -writer hello.pug

import "net/http"

func main() {
    http.HandleFunc("/", func(wr http.ResponseWriter, req *http.Request) {
        pug_hello("pug", wr)
    })
    http.ListenAndServe(":8080", nil)
}

output at localhost:8080

<!DOCTYPE html><html><body><p>Hello pug!</p></body></html>
github.com/Joker/pug package

generate html/template at runtime (This case is slightly slower and doesn't support[^2] all features of pug.go)

package main

import (
    "fmt"
    "html/template"
    "net/http"

    "github.com/Joker/pug"
)

func handler(w http.ResponseWriter, r *http.Request) {
    pugTpl, _ := pug.Parse("pug", []byte("doctype 5\n html: body: p Hello #{.Word} !"))
    goTpl, _ := template.New("html").Parse(pugTpl)

    fmt.Printf("output:%s\n\n", hpp.PrPrint(pugTpl))
    goTpl.Execute(w, struct{ Word string }{"pug"})
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

console output

<!DOCTYPE html>
<html>
    <body>
        <p>Hello {{.Word}} !</p>
    </body>
</html>

output at localhost:8080

<!DOCTYPE html><html><body><p>Hello pug !</p></body></html>

Performance

The data of chart comes from SlinSo/goTemplateBenchmark. chart

Custom filter :go

This filter is used as helper for command line tool
(to set imports, function name and parameters).
Filter may be placed at any nesting level.
When pug used as library :go filter is not needed.

Nested filter :func
:go:func
    CustomNameForTemplateFunc(any []int, input string, args map[string]int)

:go:func(name)
    OnlyCustomNameForTemplateFunc

:go:func(args)
    (only string, input float32, args uint)
Nested filter :import
:go:import
    "github.com/Joker/pug"
    github.com/Joker/hpp
note

[^1]: Usage: ./pug [OPTION]... [FILE]...
-basedir string base directory for templates (default "./") -d string directory for generated .go files (default "./") -inline inline HTML in generated functions -pkg string package name for generated files (default "pug") -prepend string prepend to generated files e.g for build tags -stdbuf use bytes.Buffer [default bytebufferpool.ByteBuffer] -stdlib use stdlib functions -writer use io.Writer for output [^2]: Runtime html/template generation doesn't support the following features:
=> means it generate the folowing template
``` for => "{{/* %s, %s /}}{{ range %s }}" for if => "{{ if gt len %s 0 }}{{/ %s, %s */}}{{ range %s }}"

multiline code     =>  "{{/* %s */}}"
inheritance block  =>  "{{/* block */}}"

case statement     =>  "{{/* switch %s */}}"
when               =>  "{{/* case %s: */}}"
default            =>  "{{/* default: */}}"
```
You can change this behaviour in [`config.go`](https://github.com/Joker/pug/blob/master/config.go#L24) file.  
Partly this problem can be solved by [custom](https://pkg.go.dev/text/template#example-Template-Func) functions.  

Documentation

Overview

pug.go - template engine. Package implements pug-lang templates for generating Go html/template output.

Index

Constants

This section is empty.

Variables

View Source
var NewStr = []byte("\n")

NewStr should be "\n" or "\r\n" for windows

View Source
var ReadFunc = os.ReadFile
View Source
var TabSize = 4
View Source
var TabStr = []byte("    ")

TabStr - tab size

Functions

func ByPrint

func ByPrint(in []byte) []byte

func Config

func Config(c ReplaceTokens)

Config is responsible for configuring the behavior of the Pug template engine. It tells the engine how to generate Go code based on the Pug templates. parameter c of type pug.ReplaceTokens holds a set of replacement patterns and settings that control the code generation process. GolangMode: true: Indicates that the engine should generate Go code. In essence, pug.Config(golang) sets up the rules and patterns that the Pug template engine will follow when it parses the .pug templates and generates the corresponding Go code.

func Format

func Format(r io.Reader, w io.Writer)

func New

func New(name string) *tree

New allocates a new parse tree with the given name.

func PHPformat

func PHPformat(in []byte) []byte

func Parse

func Parse(fname string, text []byte) (string, error)

Parse parses the template definition string to construct a representation of the template for execution.

Trivial usage:

package main

import (
	"fmt"
	"html/template"
	"net/http"

	"github.com/shaban/pug"
)

func handler(w http.ResponseWriter, r *http.Request) {
	pugTpl, _ := pug.Parse("pug", []byte("doctype 5\n html: body: p Hello #{.Word}!"))
	goTpl, _ := template.New("html").Parse(pugTpl)

	goTpl.Execute(w, struct{ Word string }{"pug"})
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

Output:

<!DOCTYPE html><html><body><p>Hello pug!</p></body></html>

func ParseFile

func ParseFile(fname string) (string, error)

ParseFile parse the pug template file in given filename

func ParseFileFromFileSystem

func ParseFileFromFileSystem(fname string, fs http.FileSystem) (str string, err error)

ParseFileFromFileSystem parse template file in context of a http.FileSystem (supports embedded files)

func ParseWithFileSystem

func ParseWithFileSystem(fname string, text []byte, fs http.FileSystem) (str string, err error)

ParseWithFileSystem parse in context of a http.FileSystem (supports embedded files)

func PrPrint

func PrPrint(in string) string

func Print

func Print(r io.Reader) []byte

func UseGoFilter

func UseGoFilter() *goFilter

global variable access (goFlt)

Types

type ReplaceTokens

type ReplaceTokens struct {
	GolangMode bool
	TagBgn     string
	TagEnd     string
	TagVoid    string
	TagArgEsc  string
	TagArgUne  string
	TagArgStr  string
	TagArgAdd  string
	TagArgBgn  string
	TagArgEnd  string

	CondIf     string
	CondUnless string
	CondCase   string
	CondWhile  string
	CondFor    string
	CondEnd    string
	CondForIf  string

	CodeForElse   string
	CodeLongcode  string
	CodeBuffered  string
	CodeUnescaped string
	CodeElse      string
	CodeElseIf    string
	CodeCaseWhen  string
	CodeCaseDef   string
	CodeMixBlock  string

	TextStr     string
	TextComment string

	MixinBgn         string
	MixinEnd         string
	MixinVarBgn      string
	MixinVar         string
	MixinVarRest     string
	MixinVarEnd      string
	MixinVarBlockBgn string
	MixinVarBlock    string
	MixinVarBlockEnd string
}

Directories

Path Synopsis
cmd
pug
Code generated by "pug.go"; DO NOT EDIT.
Code generated by "pug.go"; DO NOT EDIT.

Jump to

Keyboard shortcuts

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