Scriggo

repository·main·Indexed 20 days ago

https://github.com/open2b/scriggo

A fast, embeddable pure Go language interpreter and powerful template engine. Scriggo allows developers to use Go as a scripting language within templates and provides native support for Markdown. It features template inheritance, macros, partials, and contextual autoescaping, with support for multiple formats including HTML, CSS, JavaScript, and JSON. The toolset includes a CLI for building static sites, generating package importers, and compiling to WebAssembly (Wasm).

Tokens
11K
Snippets
38
Records
48
Agent score
64%

What's inside scriggo

  1. Use the Scriggo CLI

    main

    The scriggo command is a command-line tool used for managing and executing Scriggo templates. It supports HTML and Markdown, and provides capabilities for:

    • Serving and building templates: Render templates with HTML and Markdown support.
    • Interpreter initialization: Initialize an interpreter for running Scriggo programs written in Go.
    • Code generation: Generate code for package importers.
  2. Scriggo template syntax and features

    main

    Scriggo templates use a syntax that allows for powerful logic using Go as the scripting language. Key features include:

    • Inheritance: Use {% extends "layout.html" %} to extend a base template.
    • Imports: Use {% import "module.html" %} to include other files.
    • Macros: Define reusable blocks with {% macro Name %} ... {% end %}.
    • Partials: Render other templates using {{ render "filename.html" }}.
    • Contextual Autoescaping: Built-in security for rendering content.
    • Multi-format support: Templates can be written in plain text, HTML, Markdown, CSS, JavaScript, and JSON.
    {% extends "layout.html" %}
    {% import "banners.html" %}
    {% macro Body %}
        <ul
          {% for product in products %}
          <li><a href="{{ product.URL }}">{{ product.Name }}</a></li>
          {% end %}
        </ul
        {{ render "pagination.html" }}
        {{ Banner() }}
    {% end %}
  3. Execute a Scriggo template in your Go application

    main

    To use Scriggo as a template engine, use scriggo.BuildTemplate to compile a specific file from a scriggo.Files filesystem. You can pass BuildOptions to define global variables and functions (using native.Declarations) that will be available within the template. Once built, use template.Run to render the template to an io.Writer.

    // Build and run a Scriggo template.
    package main
    
    import (
    	"os"
    
    	"github.com/open2b/scriggo"
    	"github.com/open2b/scriggo/builtin"
    	"github.com/open2b/scriggo/native"
    )
    
    func main() {
    
        // Content of the template file to run.
        content := []byte(`
        <!DOCTYPE html>
        <html>
        <head>Hello</head> 
        <body
            Hello, {{ capitalize(who) }}!
        </body>
        </html>
        `)
    
        // Create a file system with the file of the template to run.
        fsys := scriggo.Files{"index.html": content}
    
        // Declare some globals.
        var who = "world"
        opts := &scriggo.BuildOptions{
            Globals: native.Declarations{
                "who":        &who,               // global variable
                "capitalize": builtin.Capitalize, // global function
            },
        }
    
        // Build the template.
        template, err := scriggo.BuildTemplate(fsys, "index.html", opts)
        if err != nil {
            panic(err)
        }
     
        // Run the template and print it to the standard output.
        err = template.Run(os.Stdout, nil, nil)
        if err != nil {
            panic(err)
        }
    
    }
  4. Compile Scriggo to WebAssembly (Wasm) on Linux

    main

    To compile Scriggo for use in a web environment on Linux, set the Go target environment to JavaScript/Wasm, import the necessary packages into a Go file, and build the .wasm binary. You must also copy the wasm_exec.js file from your Go installation to your project directory to enable the Wasm runtime in the browser.

    export GOOS=js
    export GOARCH=wasm
    scriggo import -v -o packages.go
    go build -tags osusergo,netgo -trimpath -o scriggo.wasm
    cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
  5. Compile Scriggo to WebAssembly (Wasm) on Windows

    main

    To compile Scriggo for use in a web environment on Windows, set the Go target environment to JavaScript/Wasm using SET, import the packages, and build the .wasm binary. You must copy wasm_exec.js from your Go installation directory (typically C:\Program Files\Go\misc\wasm\wasm_exec.js) to your project directory.

    SET GOOS=js
    SET GOARCH=wasm
    scriggo import -v -o packages.go
    go build -tags osusergo,netgo -trimpath -o scriggo.wasm
    copy "C:\Program Files\Go\misc\wasm\wasm_exec.js" .
  6. Build a Scriggo-compatible highlight.js file

    main

    To use Scriggo's syntax highlighting with highlight.js, you must build a custom version of the highlight.js library that includes the scriggo.js language definition. This requires node and the highlight.js source repository.

    # 1. Clone highlight.js
    git clone https://github.com/highlightjs/highlight.js
    cd highlight.js
    
    # 2. Checkout a specific release tag (e.g., 11.2.0)
    git checkout 11.2.0
    
    # 3. Install dependencies
    npm install
    
    # 4. Copy the Scriggo language definition into highlight.js
    cp <path to Scriggo repo>/highlighters/highlight.js/scriggo.js src/languages
    
    # 5. Build the syntax source with Scriggo support
    node tools/build.js scriggo
    
    # 6. Copy the built file to your destination
    cp build/highlight.js <destination directory>
    # OR for the minified version:
    cp build/highlight.min.js <destination directory>
  7. Execute a Scriggo program in your Go application

    main

    You can execute Scriggo programs (Go-like source code) by building them from a file system and then running the resulting program. Use scriggo.Build to compile the source and program.Run to execute it. The source code is provided via a scriggo.Files map.

    package main
    
    import "github.com/open2b/scriggo"
    
    func main() {
    
        // src is the source code of the program to run.
        src := []byte(`
            package main
    
            func main() {
                println("Hello, World!")
            }
        `)
    
        // Create a file system with the file of the program to run.
        fsys := scriggo.Files{"main.go": src}
    
        // Build the program.
        program, err := scriggo.Build(fsys, nil)
        if err != nil {
            panic(err)
        }
     
        // Run the program.
        err = program.Run(nil)
        if err != nil {
            panic(err)
        }
    
    }
  8. Implement FormatFS for custom format detection

    main

    If you want Scriggo to determine file formats using logic other than file extensions, implement the FormatFS interface. This interface embeds fs.FS and adds a Format(name string) (Format, error) method.

    type MyFormatFS interface {
    	fs.FS
    	Format(name string) (scriggo.Format, error)
    }
  9. Scriggofile Syntax and Commands

    main

    A Scriggofile is a configuration file used to define how Go code is generated. It supports several top-level commands to configure the package name, variable names for imports, target operating systems, and package imports.

    Commands

    SET

    Used to configure the generation environment.

    • SET VARIABLE <name>: Sets the variable name used for imported packages in the generated code. Defaults to packages.
    • SET PACKAGE <name>: Sets the name of the Go package to be generated. Defaults to main.

    GOOS

    Specifies the target operating systems for which the code should be generated. Multiple values can be provided.

    • Example: GOOS linux darwin amd64

    IMPORT

    Defines package imports for the generated code.

    • Standard Library: Use IMPORT STANDARD LIBRARY to include the Go standard library.
    • External Packages: Use IMPORT <path> to import a specific package.
    • Aliasing: Use the AS option to alias an import. Example: IMPORT github.com/user/pkg AS mypkg.
    • Filtering Exports:
      • INCLUDING <name1> <name2> ...: Only include the specified exported names.
      • EXCLUDING <name1> <name2> ...: Exclude the specified exported names.
    • Case Sensitivity: Use NOT CAPITALIZED to specify that exported names must not be capitalized (this can only be used after AS main).

    Syntax Rules

    • Lines starting with # are treated as comments.
    • Empty lines are ignored.
    • Commands are case-insensitive (e.g., set, Set, and SET are equivalent).
  10. How Scriggo handles Go declarations

    main

    When Scriggo processes a Go package, it maps exported package-level identifiers to Scriggo-compatible values:

    Go EntityScriggo Mapping
    Untyped String Constantnative.UntypedStringConst("value")
    Untyped Bool Constantnative.UntypedBooleanConst(true)
    Untyped Numeric Constantnative.UntypedNumericConst("value")
    Functionpackage.FunctionName
    Variable&package.VariableName
    Type Namereflect.TypeFor[package.TypeName]()

    Note on Generics: Scriggo currently skips generic functions, generic types, and general interfaces during the extraction process.

  11. Configure a Scriggofile

    main

    A Scriggofile (or .Scriggofile) uses a Dockerfile-like syntax to define the environment for the Scriggo interpreter. Instructions are case-insensitive.

    Core Instructions:

    • IMPORT STANDARD LIBRARY: Makes Go standard library packages available.
    • IMPORT <package>: Makes a specific package importable.
    • IMPORT <package> [INCLUDING|EXCLUDING] <names>: Fine-grained control over exported names.
    • IMPORT <package> AS <alias>: Imports a package under a different name.
    • IMPORT <package> AS main [NOT CAPITALIZED]: Imports a package as the main package (allows import . "path" behavior). NOT CAPITALIZED makes exported names lowercase in templates.
    • SET VARIABLE <name>: Sets the name of the native.Importer variable (used by import command).
    • SET PACKAGE <name>: Sets the package name for generated Go code.
    • GOOS <os>: Restricts the interpreter to specific operating systems (e.g., GOOS linux windows).
    # Example Scriggofile
    IMPORT STANDARD LIBRARY
    IMPORT math AS m
    SET VARIABLE myPackages