### Install OnceScopeMiddleware
Source: https://gsxhq.github.io/guide/patterns/render-once.html
Wrap the application handler or router to initialize the request scope.
```go
handler := OnceScopeMiddleware(mux)
```
--------------------------------
### Start the development server
Source: https://gsxhq.github.io/guide/getting-started.html
Launch the development server to enable live reloading during development.
```sh
npm run dev
```
--------------------------------
### Interactive project initialization
Source: https://gsxhq.github.io/guide/cli.html
Run init without arguments to trigger an interactive setup process.
```bash
gsx init
```
--------------------------------
### Initialize a new gsx project
Source: https://gsxhq.github.io/guide/getting-started.html
Install the gsx CLI and scaffold a new project using the starter template.
```sh
go install github.com/gsxhq/gsx/cmd/gsx@latest
gsx init hello-gsx --yes
cd hello-gsx
```
--------------------------------
### Run the development server
Source: https://gsxhq.github.io/guide/dev-loop.html
Starts the development loop to watch for file changes and manage the server.
```sh
gsx dev
```
--------------------------------
### Install VS Code extension
Source: https://gsxhq.github.io/guide/editor.html
Command to install the GSX extension via the VS Code CLI.
```bash
code --install-extension gsxhq.gsx
```
--------------------------------
### Start GSX Language Server
Source: https://gsxhq.github.io/guide/cli.html
Initializes the language server over standard input and output for editor integration.
```bash
gsx lsp
```
--------------------------------
### Rendered output of GoBlock example
Source: https://gsxhq.github.io/guide/syntax/raw-go.html
The resulting HTML output from the FullName component.
```html
Ada Lovelace
```
--------------------------------
### Define project configuration in gsx.toml
Source: https://gsxhq.github.io/guide/config.html
Example of a multi-section configuration file defining packages, presets, and tool settings.
```toml
filter_packages = ["example.com/app/templatefuncs"]
url_presets = ["htmx"]
class_merger = "example.com/app/twcfg.Merge"
[dev]
web = ["pnpm", "vite"]
[filters]
url = "github.com/jackielii/structpages.URLFor"
[formatter]
print_width = 100
imports = "goimports"
[minify]
css = "full"
js = "full"
```
--------------------------------
### Check GSX Version
Source: https://gsxhq.github.io/guide/cli.html
Displays the installed version, including commit details and Go toolchain information.
```bash
gsx version
```
--------------------------------
### Implement Tailwind class merger
Source: https://gsxhq.github.io/guide/config.html
Example implementation of a class merger using the tailwind-merge-go library.
```go
package twcfg
import "github.com/jackielii/tailwind-merge-go/pkg/twmerge"
var merger = twmerge.CreateTwMerge(twmerge.GetDefaultConfig())
func Merge(classes []string) string { return merger(classes) }
```
--------------------------------
### Format GSX files
Source: https://gsxhq.github.io/guide/cli.html
Rewrite .gsx files in place recursively starting from the current directory.
```bash
gsx fmt -w .
```
--------------------------------
### Initialize a new project
Source: https://gsxhq.github.io/guide/cli.html
Scaffold a new project directory using the simple template.
```bash
gsx init myapp
```
--------------------------------
### Initialize project syntax
Source: https://gsxhq.github.io/guide/cli.html
Syntax reference for the init command.
```text
gsx init [dir] [flags]
```
--------------------------------
### Define a region
Source: https://gsxhq.github.io/guide/syntax/processing-instructions.html
Wrap temporary content using start and end tags to define a region.
```gsx
component Feed() {
Loading…
}
```
```html
Loading…
```
--------------------------------
### Initialize custom gsx binary
Source: https://gsxhq.github.io/guide/extensions.html
The entry point for a project-owned gsx command using gen.Main.
```go
package main
import "github.com/gsxhq/gsx/gen"
func main() {
gen.Main()
}
```
--------------------------------
### Reproduce benchmark snapshot
Source: https://gsxhq.github.io/guide/performance.html
Commands to clone the repository, checkout specific commits, and execute the benchmark suite.
```sh
git clone https://github.com/gsxhq/gsx
git clone https://github.com/gsxhq/gsx-bench
git -C gsx checkout cb5ec7c2b477a0fa6c6690eead3f815dd923ce64
git -C gsx-bench checkout 26b68db36773cc0f5f336f51d5f30388220b3f98
cd gsx-bench
GOMAXPROCS=32 go test -run '^$' -bench . -benchmem -count=10 . > results.txt
go run golang.org/x/perf/cmd/benchstat@v0.0.0-20260709024250-82a0b07e230d results.txt
```
--------------------------------
### Build for production
Source: https://gsxhq.github.io/guide/getting-started.html
Bundle assets, generate Go code, and compile the final binary for deployment.
```sh
npm run build
go tool gsx generate
go build -o app
./app
```
--------------------------------
### Non-interactive project initialization
Source: https://gsxhq.github.io/guide/cli.html
Use the --yes flag to bypass prompts during project scaffolding.
```bash
gsx init myapp --module example.com/acme/myapp --yes
```
--------------------------------
### Execute project binary
Source: https://gsxhq.github.io/guide/extensions.html
Run the custom project binary to apply programmatic options.
```bash
go run ./cmd/gsx generate ./...
```
--------------------------------
### Use line comments between child nodes
Source: https://gsxhq.github.io/guide/syntax/comments.html
A line starting with // between child nodes is treated as a source-only comment.
```gsx
package views
component Nav() {
}
```
```html
```
--------------------------------
### Generate the renderer package
Source: https://gsxhq.github.io/guide/patterns/package-renderers.html
Execute the generation command to bootstrap declarations from the local .gsx source.
```bash
go tool gsx generate ./ds/renderers
```
--------------------------------
### gen.Main
Source: https://gsxhq.github.io/guide/extensions.html
The entry point for a custom gsx binary. It accepts optional configuration functions to customize formatting and minification behavior.
```APIDOC
## func gen.Main(...options)
### Description
Initializes the gsx command-line tool with custom programmatic configurations. Options provided here take precedence over settings in gsx.toml.
### Parameters
- **options** (variadic) - Optional - Configuration functions such as WithCSSFormatter, WithJSFormatter, WithCSSMinifier, WithJSMinifier, and WithMinifyLevel.
```
--------------------------------
### Configuring the formatter
Source: https://gsxhq.github.io/guide/config.html
Set global formatting preferences for line width, tab width, and import handling.
```toml
[formatter]
print_width = 100
tab_width = 4
imports = "goimports"
```
--------------------------------
### Use singleton component
Source: https://gsxhq.github.io/guide/patterns/render-once.html
Declare a package-level handle and wrap the singleton content with the Once component.
```gsx
var dialogContainerOnce = NewOnce()
component DialogContainer() {
}
```
--------------------------------
### Inspect project configuration
Source: https://gsxhq.github.io/guide/cli.html
Display the resolved project configuration or output it as JSON for automated scripts.
```bash
gsx info
```
```bash
gsx info --json
```
--------------------------------
### Run development loop without web server
Source: https://gsxhq.github.io/guide/cli.html
Execute the development loop without the default Vite front-door.
```bash
gsx dev --no-web
```
--------------------------------
### Configure Neovim LSP
Source: https://gsxhq.github.io/guide/editor.html
Lua configuration for Neovim's built-in LSP client to support GSX files.
```lua
vim.filetype.add({ extension = { gsx = "gsx" } })
vim.api.nvim_create_autocmd("FileType", {
pattern = "gsx",
callback = function(args)
vim.lsp.start({
name = "gsx",
cmd = { "gsx", "lsp" },
root_dir = vim.fs.root(args.buf, { "gsx.toml", "go.mod" }),
})
end,
})
```
--------------------------------
### CLI usage syntax
Source: https://gsxhq.github.io/guide/cli.html
General syntax for executing gsx commands.
```text
gsx [global flags] [arguments]
```
--------------------------------
### Implement OnceHandle helper
Source: https://gsxhq.github.io/guide/patterns/render-once.html
Define the handle and middleware logic to track component rendering state across a request context.
```go
package app
import (
"context"
"net/http"
"sync"
"sync/atomic"
)
type OnceHandle struct{ id int64 }
var onceIndex atomic.Int64
func NewOnce() *OnceHandle {
return &OnceHandle{id: onceIndex.Add(1)}
}
type onceState struct {
mu sync.Mutex
seen map[*OnceHandle]struct{}
}
type onceKeyT struct{}
func (h *OnceHandle) firstRender(ctx context.Context) bool {
state, _ := ctx.Value(onceKeyT{}).(*onceState)
if state == nil {
return true
}
state.mu.Lock()
defer state.mu.Unlock()
if _, seen := state.seen[h]; seen {
return false
}
state.seen[h] = struct{}{}
return true
}
func withOnceScope(ctx context.Context) context.Context {
if state, _ := ctx.Value(onceKeyT{}).(*onceState); state != nil {
return ctx
}
return context.WithValue(ctx, onceKeyT{}, &onceState{
seen: make(map[*OnceHandle]struct{}),
})
}
func OnceScopeMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := withOnceScope(r.Context())
next.ServeHTTP(w, r.WithContext(ctx))
})
}
```
--------------------------------
### Configuration Precedence Order
Source: https://gsxhq.github.io/guide/config.html
Displays the hierarchy of settings application from highest to lowest priority.
```text
programmatic option > environment override > gsx.toml > built-in default
```
--------------------------------
### Define and use a component with attributes
Source: https://gsxhq.github.io/guide/syntax/props.html
Demonstrates a component signature using loose parameters including a gsx.Node and gsx.Attrs.
```gsx
package views
import "github.com/gsxhq/gsx"
component Button(variant string, children gsx.Node, attrs gsx.Attrs) {
}
component Page() {
}
```
```html
```
--------------------------------
### Render gsx into html/template
Source: https://gsxhq.github.io/guide/syntax/interop.html
Render the node to a buffer and pass the result as template.HTML.
```go
var body bytes.Buffer
if err := views.Page(props).Render(ctx, &body); err != nil {
return err
}
return tmpl.Execute(w, struct{ Body template.HTML }{
Body: template.HTML(body.String()),
})
```
--------------------------------
### Declare and render a GSX component
Source: https://gsxhq.github.io/playground.html
Defines a Greeting component that accepts a name and count, then renders it with specific arguments.
```go
package views
component Greeting(name string, count int) {
Hello, { name }! You have { count } messages.
}
render — the expression to renderGreeting("World", 3)
```
--------------------------------
### Declare a basic component
Source: https://gsxhq.github.io/guide/learn.html
Define a component in a .gsx file using Go syntax and HTML markup.
```gsx
package views
component Greeting(name string) {
Hello, {name}
}
```
--------------------------------
### Verify gsx binary
Source: https://gsxhq.github.io/guide/editor.html
Commands to check the version of the gsx binary and locate Go binary directories.
```bash
gsx version
```
```bash
go env GOBIN GOPATH
```
--------------------------------
### Define and call components across files
Source: https://gsxhq.github.io/guide/syntax/composition.html
Components in the same package are called by name, while imported components use their Go package qualifier.
```gsx
package views
import "github.com/gsxhq/gsx"
component Button(label string) {
}
component Card(title string, children gsx.Node) {
{ title }
{ children }
}
```
```gsx
package views
type HomePage struct {
Title string
}
component (p HomePage) Render() {
}
```
```html
Dashboard
```
--------------------------------
### Render full HTML documents
Source: https://gsxhq.github.io/guide/syntax/elements.html
Shows how to render a complete HTML document including the DOCTYPE declaration.
```gsx
package views
component Page(title string) {
{ title }
hi
}
```
```html
Homehi
```
--------------------------------
### Define package and imports
Source: https://gsxhq.github.io/guide/syntax/basic-syntax.html
Standard Go package declaration and import of the gsx runtime package.
```gsx
package views
import "github.com/gsxhq/gsx"
func wrap(n gsx.Node) gsx.Node { return n }
```
--------------------------------
### Render html/template into gsx
Source: https://gsxhq.github.io/guide/syntax/interop.html
Render the template to a buffer and pass the result through gsx.Raw.
```go
var body bytes.Buffer
if err := tmpl.Execute(&body, data); err != nil {
return err
}
return views.Shell(gsx.Raw(body.String())).Render(ctx, w)
```
--------------------------------
### Enable the development panel
Source: https://gsxhq.github.io/guide/dev-loop.html
Add this import to the Vite client entry file to enable the status overlay.
```js
import "virtual:gsx-devpanel";
```
--------------------------------
### Use elements as values
Source: https://gsxhq.github.io/guide/syntax/elements.html
Demonstrates assigning elements and fragments to variables and using them as expressions.
```gsx
package views
var help = Help
var empty = <>
No results
Try another search.
>
component Page() {
{help}{empty}
}
```
--------------------------------
### Bind markup attributes to component parameters
Source: https://gsxhq.github.io/guide/syntax/props.html
Shows how markup attributes map to component parameters by exact name and how to pass struct-based props.
```gsx
package views
type Props struct {
Title string
}
component Greeting(name string) {
P
```
--------------------------------
### Set base directory with global flag
Source: https://gsxhq.github.io/guide/cli.html
Use the -C flag to specify a base directory for project paths and configuration.
```bash
gsx -C ./web generate .
```
--------------------------------
### Define typed component inputs
Source: https://gsxhq.github.io/guide/learn.html
Use Go parameters to define component inputs, which are then passed as attributes.
```gsx
component Meter(value int) {
{value}%
}
component Dashboard() {
}
```
--------------------------------
### Define component inputs with structs
Source: https://gsxhq.github.io/guide/syntax/props.html
Use an ordinary struct parameter when keyed Go construction is preferred for component options.
```gsx
type CardOptions struct {
Title string
Featured bool
}
component Card(opts CardOptions) {
{opts.Title}
}
component Page() {
}
```
--------------------------------
### Basic gsx.toml Configuration
Source: https://gsxhq.github.io/guide/config.html
Defines the development command and custom URL filters for the project.
```toml
# gsx.toml
[dev]
web = ["pnpm", "vite"]
[filters]
url = "github.com/jackielii/structpages.URLFor"
```
--------------------------------
### Define a component with multiple roots using fragments
Source: https://gsxhq.github.io/guide/syntax/fragments.html
Use the <>...> syntax to group sibling nodes without creating an additional HTML wrapper element.
```gsx
package views
component Pair(a string, b string) {
<>{ a }{ b }>
}
```
--------------------------------
### Enable format and organize imports on save
Source: https://gsxhq.github.io/guide/editor.html
VS Code settings to automatically format and organize imports for GSX files.
```json
"[gsx]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
}
```
--------------------------------
### Handle raw-text elements
Source: https://gsxhq.github.io/guide/syntax/elements.html
Demonstrates how script and style tags treat content as literal text, requiring specific interpolation syntax.
```gsx
package views
component Tracker() {
}
```
```html
```
--------------------------------
### Define tags and nesting in GSX
Source: https://gsxhq.github.io/guide/syntax/elements.html
Demonstrates component definition with nested HTML elements and dynamic Go expression interpolation.
```gsx
package views
component Card(title string, body string) {
{title}
{body}
}
```
--------------------------------
### Register custom minifiers
Source: https://gsxhq.github.io/guide/extensions.html
Configure custom minification logic and set minification levels for CSS and JavaScript.
```go
gen.Main(
gen.WithCSSMinifier(minifyCSS),
gen.WithJSMinifier(minifyJavaScript),
gen.WithMinifyLevel(gen.MinifyFull, gen.MinifyFull), // CSS, JavaScript
)
```
```go
func minifyCSS(css string) (string, error)
func minifyJavaScript(js string) (string, error)
```
--------------------------------
### Check formatting in CI
Source: https://gsxhq.github.io/guide/cli.html
Use the -l flag to list files that would change, which exits with status 1 if any differences are found.
```bash
gsx fmt -l .
```
--------------------------------
### Define and use generic components
Source: https://gsxhq.github.io/guide/syntax/composition.html
Declare Go type parameters after the component name to allow GSX to infer types from supplied inputs.
```gsx
package views
component Badge[T string | int](value T) {
{ value }
}
component Page() {
}
```
```html
new42
```
--------------------------------
### Implement a Flush helper in Go
Source: https://gsxhq.github.io/guide/patterns/streaming-flush.html
Define a custom gsx.Node that uses http.NewResponseController to flush the current writer buffer.
```go
package app
import (
"context"
"errors"
"io"
"net/http"
"github.com/gsxhq/gsx"
)
// Flush streams whatever has been written so far to the client, invokable as a
// bare tag. It writes no HTML of its own.
func Flush() gsx.Node {
return gsx.Func(func(ctx context.Context, w io.Writer) error {
rw, ok := w.(http.ResponseWriter)
if !ok {
return nil
}
if err := http.NewResponseController(rw).Flush(); err != nil && !errors.Is(err, http.ErrNotSupported) {
return err
}
return nil
})
}
```
--------------------------------
### Define Development Commands
Source: https://gsxhq.github.io/guide/config.html
Specify custom commands for web and backend processes in the [dev] section.
```toml
[dev]
web = ["pnpm", "vite"]
build = ["go", "build", "-tags", "dev", "-o", "tmp/app", "."]
run = ["tmp/app"]
log = "tmp/dev.log"
```
--------------------------------
### Run in watch mode
Source: https://gsxhq.github.io/guide/cli.html
Monitor source files for changes and trigger regeneration automatically.
```bash
gsx generate --watch
```
```bash
gsx generate --watch --format=ndjson
```
--------------------------------
### Iterating with Range
Source: https://gsxhq.github.io/guide/syntax/control-flow.html
Use for/range loops to render markup for each item in a collection.
```gsx
package views
type Item struct {
Name string
Count int
}
component List(items []Item) {
{ for _, it := range items {
{ it.Name }: { it.Count }
} }
}
```
```html
alpha: 1
beta: 2
```
--------------------------------
### gsx info
Source: https://gsxhq.github.io/guide/cli.html
Inspects the resolved configuration for the current project.
```APIDOC
## gsx info
### Description
Displays the active configuration path and resolved project settings. Supports human-readable output or JSON for automation.
### Parameters
#### Flags
- **--json** (flag) - Optional - Output inspection results in JSON format.
```
--------------------------------
### Applying URL presets
Source: https://gsxhq.github.io/guide/config.html
Enable built-in URL attribute classification for specific frameworks like htmx.
```toml
url_presets = ["htmx"]
```
--------------------------------
### Core Types and Functions
Source: https://gsxhq.github.io/guide/syntax/std-functions.html
Fundamental interfaces and adapters for rendering components.
```APIDOC
## Node
`type Node interface { Render(ctx context.Context, w io.Writer) error }`
## Func
`type Func func(ctx context.Context, w io.Writer) error`
Adapts a render function to the `Node` interface.
```
--------------------------------
### Include local styles and scripts
Source: https://gsxhq.github.io/guide/learn.html
Embed CSS and JavaScript directly within the component definition.
```gsx
component Notice(message string) {
{message}
}
```
--------------------------------
### Override build and run commands
Source: https://gsxhq.github.io/guide/cli.html
Specify custom build and execution commands for the current session.
```bash
gsx dev --build "go build -o ./tmp/app ./cmd/site" --run "./tmp/app"
```
--------------------------------
### Define build-constrained components
Source: https://gsxhq.github.io/guide/syntax.html
Use Go build tags to define mutually exclusive component variants for different platforms.
```gsx
// platform_linux.gsx
//go:build linux
package views
component PlatformName() {
Linux
}
// platform_other.gsx
//go:build !linux
package views
component PlatformName() {
Other
}
```
--------------------------------
### Render templ from gsx
Source: https://gsxhq.github.io/guide/syntax/interop.html
Accept a gsx.Node and pass a templ component to it.
```gsx
component Shell(body gsx.Node) {
{body}
}
```
```go
page := views.Shell(templComponent) // templComponent is a templ.Component
```
--------------------------------
### Script Tag Interpolation
Source: https://gsxhq.github.io/guide/syntax/javascript.html
Shows how to inject Go values into a JavaScript context within a script tag using interpolation.
```gsx
package views
type AppState struct {
Tab string
Open bool
}
component Shell(state AppState) {
}
```
```html
```
--------------------------------
### Compose classes with conditions
Source: https://gsxhq.github.io/guide/syntax/styling.html
Use a list of strings and conditional maps to define element classes. The order of elements is preserved in the rendered output.
```gsx
package views
component Tag(label string, active bool) {
{ label }
}
```
```html
stable
```
```gsx
```
--------------------------------
### Inject CSP Nonces
Source: https://gsxhq.github.io/guide/syntax/escaping.html
Use gsx.WithNonce to attach a cryptographically secure nonce to the render context for script and style tags.
```go
nonce := newNonce() // Generate this with a cryptographically secure source.
w.Header().Set("Content-Security-Policy",
"script-src 'nonce-"+nonce+"'; style-src 'nonce-"+nonce+"'")
page.Render(gsx.WithNonce(r.Context(), nonce), w)
```
--------------------------------
### Pin gsx runtime and CLI versions
Source: https://gsxhq.github.io/guide/status.html
Use these commands to pin the gsx runtime and CLI to a specific tagged release.
```sh
go get github.com/gsxhq/gsx@v0.1.0
go get -tool github.com/gsxhq/gsx/cmd/gsx@v0.1.0
```
--------------------------------
### Declare local values with GoBlock
Source: https://gsxhq.github.io/guide/syntax/raw-go.html
Use a GoBlock to execute statements and declare local variables that are accessible to subsequent children.
```gsx
package views
component FullName(first string, last string) {
{{ full := first + " " + last }}
{ full }
}
```
--------------------------------
### Create Once component
Source: https://gsxhq.github.io/guide/patterns/render-once.html
Guard component children using the firstRender method of the OnceHandle.
```gsx
component Once(handle *OnceHandle) {
{ if handle.firstRender(ctx) { { children } } }
}
```
--------------------------------
### Configure asset minification
Source: https://gsxhq.github.io/guide/config.html
Set the minification level for CSS and JavaScript assets in the configuration file.
```toml
[minify]
css = "full"
js = "full"
```
--------------------------------
### Define GSX attributes with expressions and literals
Source: https://gsxhq.github.io/guide/syntax/attributes.html
Use braces for Go expressions and typed literals like js`...` or css`...` for dynamic content.
```gsx
Profile
...
```
--------------------------------
### Render trusted HTML with gsx.Raw
Source: https://gsxhq.github.io/guide/syntax/raw-html.html
Use gsx.Raw to output strings as raw HTML. Ensure the input is sanitized to prevent XSS vulnerabilities.
```gsx
package views
import "github.com/gsxhq/gsx"
// ArticleBody renders pre-sanitized HTML from a CMS or Markdown converter.
// { gsx.Raw(html) } emits the string verbatim — no entity encoding.
component ArticleBody(html string) {
{ gsx.Raw(html) }
}
```
```html
Hello & World
```
--------------------------------
### Generate sibling files
Source: https://gsxhq.github.io/guide/cli.html
Run generation on the current directory or specific paths.
```bash
gsx generate
gsx generate ./views ./email
```
--------------------------------
### Register custom CSS and JavaScript formatters
Source: https://gsxhq.github.io/guide/extensions.html
Configure custom formatting callbacks for embedded CSS and JavaScript code.
```go
gen.Main(
gen.WithCSSFormatter(formatCSS),
gen.WithJSFormatter(formatJavaScript),
)
```
```go
func(src []byte) ([]byte, error)
```
--------------------------------
### Configure Backend Upstream and Health Check
Source: https://gsxhq.github.io/guide/config.html
Set the backend upstream address and health check path for development environments.
```toml
[dev]
upstream = "http://localhost${ADDR}" # ADDR=:8890 -> http://localhost:8890
health = "/healthz"
```
--------------------------------
### Define reusable markup in gsx
Source: https://gsxhq.github.io/guide/getting-started.html
Demonstrates defining a reusable component and a package-level variable for markup interpolation.
```gsx
var footer = <>Built with gsx>
component Page(children gsx.Node) {
{children}
{footer}
}
```
--------------------------------
### Store contextual literals in local variables
Source: https://gsxhq.github.io/guide/syntax/javascript.html
Use js and css literals to assemble behavior and styles before applying them to native elements.
```gsx
component Choice(id int, color string) {
{{
behavior := js`select(@{id})`
styles := css`color:@{color}`
}}
}
```
--------------------------------
### Create lowercase wrapper components
Source: https://gsxhq.github.io/guide/syntax/basic-syntax.html
Demonstrates wrapping HTML elements with lowercase components, where the self-named tag inside the component refers to the HTML element.
```gsx
package views
import "github.com/gsxhq/gsx"
component div(children gsx.Node, attrs gsx.Attrs) {
{ children }
}
component Page() {
Hello
}
```
```html
Hello
```
--------------------------------
### Using data:image literals
Source: https://gsxhq.github.io/guide/syntax/attributes.html
Image sinks accept base64 and validated plain-text payloads, with strict rejection on navigation sinks.
```gsx
dataURL("image/png")}/>
```
--------------------------------
### Bind markup to variables
Source: https://gsxhq.github.io/guide/learn.html
Assign markup to package-level variables for reuse, using fragments to group sibling nodes.
```gsx
package views
var footer = <>Built with gsx>
component Page(children gsx.Node) {
{children}
{footer}
}
```
--------------------------------
### Define component CSS with style blocks
Source: https://gsxhq.github.io/guide/syntax/styling.html
Use style blocks to define component-scoped CSS with interpolated Go values.
```gsx
package views
component Card(w int, userColor string) {
}
```
```html
```
--------------------------------
### Define a Timestamptz renderer in .gsx
Source: https://gsxhq.github.io/guide/patterns/package-renderers.html
Create a renderer function that handles SQL NULL, infinity, and finite timestamp values by returning a gsx.Node.
```gsx
package renderers
import (
"time"
"github.com/gsxhq/gsx"
"github.com/jackc/pgx/v5/pgtype"
)
func Timestamptz(v pgtype.Timestamptz) gsx.Node {
if !v.Valid {
return <>>
}
switch v.InfinityModifier {
case pgtype.Infinity:
return
case pgtype.NegativeInfinity:
return
default:
return
}
}
```
--------------------------------
### Declare a component
Source: https://gsxhq.github.io/guide/syntax/basic-syntax.html
Defines a component with typed parameters and a markup body that implicitly returns the rendered result.
```gsx
package views
component Greeting(name string, count int) {
Hello, { name }! You have { count } messages.
}
```
```html
Hello, World! You have 3 messages.
```
--------------------------------
### Register the renderer in gsx.toml
Source: https://gsxhq.github.io/guide/patterns/package-renderers.html
Map the fully qualified pgx type to the renderer function path within the project configuration.
```toml
[renderers]
"github.com/jackc/pgx/v5/pgtype.Timestamptz" = "example.com/app/ds/renderers.Timestamptz"
```
--------------------------------
### Define void elements in GSX
Source: https://gsxhq.github.io/guide/syntax/elements.html
Shows how to use void elements like img, br, and input, which do not require closing tags.
```gsx
package views
component AvatarField(src string, alt string, disabled bool) {
}
```
```html
```
--------------------------------
### Bind Go values to attributes
Source: https://gsxhq.github.io/guide/syntax/attributes.html
Use name={expr} syntax to bind Go variables to HTML attributes.
```gsx
package views
component Link(url string, label string, count int) {
{ label }
}
```
```html
Docs
```
--------------------------------
### Registering URL attributes
Source: https://gsxhq.github.io/guide/config.html
Define custom attributes that should be treated as URLs using names, prefixes, or suffixes.
```toml
[url_attrs]
names = ["v-bind:href", "wire:navigate"]
prefixes = ["data-url-"]
suffixes = ["-url"]
```
--------------------------------
### Render gsx from templ
Source: https://gsxhq.github.io/guide/syntax/interop.html
Call a gsx component directly from a .templ file.
```gsx
import "github.com/gsxhq/gsx"
component Card(title string, children gsx.Node) {
{title}
{children}
}
```
```templ
templ Page() {
@views.Card("Welcome", nil)
}
```
--------------------------------
### Read from context in a component
Source: https://gsxhq.github.io/guide/syntax/context.html
Use an unexported key type to safely retrieve values from the context within a component.
```go
package views
import "context"
type ctxKey struct{}
// userName reads an authenticated username from the context, or falls
// back to "guest" when the value is absent.
func userName(ctx context.Context) string {
if v, ok := ctx.Value(ctxKey{}).(string); ok {
return v
}
return "guest"
}
component Greeting() {
Hello, { userName(ctx) }
}
```
```html
Hello, guest
```
--------------------------------
### Register Named Filters
Source: https://gsxhq.github.io/guide/config.html
Map short names to exported Go functions in the [filters] section and use them in templates.
```toml
[filters]
url = "github.com/jackielii/structpages.URLFor"
slug = "example.com/app/textutil.Slug"
```
```gsx
url }>Open{ title |> slug }
```
--------------------------------
### Implement class merger function signature
Source: https://gsxhq.github.io/guide/config.html
The required function signature for custom class merging logic.
```go
func([]string) string
```
--------------------------------
### Define method components
Source: https://gsxhq.github.io/guide/syntax/composition.html
Attach components to a struct receiver to share state without explicit parameter threading.
```gsx
package views
type UsersPage struct {
Title string
Sort string
}
component (p UsersPage) Page() {
```
--------------------------------
### Define explicit attributes
Source: https://gsxhq.github.io/guide/learn.html
Pass static values as standard HTML and dynamic values as Go expressions.
```gsx
component SaveButton(label string, disabled bool) {
}
```
--------------------------------
### Output diagnostics as JSON
Source: https://gsxhq.github.io/guide/cli.html
Direct diagnostic output to stdout in JSON format for programmatic consumption.
```bash
gsx generate --json ./views
```
--------------------------------
### Render client-side islands
Source: https://gsxhq.github.io/guide/syntax/interop.html
Render server-owned shell and serialized data with gsx for client-side hydration.
```gsx
component ChartIsland(data ChartData) {
}
```
--------------------------------
### Define a marker placeholder
Source: https://gsxhq.github.io/guide/syntax/processing-instructions.html
Use a marker as a void placeholder within a component.
```gsx
component Row(id string) {
}
```
```html
```
--------------------------------
### Context-aware pipeline output
Source: https://gsxhq.github.io/guide/syntax/pipelines.html
Pipelines maintain safety rules based on the output context, such as URL sinks.
```gsx
package views
component Link(u string) {
trim}>x
}
```
```html
x
```
--------------------------------
### Register helper packages
Source: https://gsxhq.github.io/guide/config.html
Register compatible exported functions from helper packages using the filter_packages configuration.
```toml
filter_packages = [
"example.com/app/templatefuncs",
"example.com/app/productfilters",
]
```
--------------------------------
### Call components with attributes
Source: https://gsxhq.github.io/guide/syntax/composition.html
Call a component by name and pass inputs as attributes. Use self-closing tags for components without nested content.
```gsx
package views
component Card(title string, featured bool, count int) {
{ title }
{ count }
}
component Page(t string, n int) {
}
```
```html
Hi
3
```
--------------------------------
### Import mode precedence
Source: https://gsxhq.github.io/guide/config.html
The hierarchy used to determine which import formatting tool is applied.
```text
gsx fmt -imports / -no-imports > [formatter].imports > goimports
```
--------------------------------
### Exposing server data with JSON islands
Source: https://gsxhq.github.io/guide/syntax/javascript.html
Embeds a Go struct into a component as a JSON script tag for client-side access.
```gsx
package views
type Config struct {
Env string
Beta bool
}
component Widget(cfg Config) {
}
```
--------------------------------
### Define a gsx component
Source: https://gsxhq.github.io/guide/vision.html
Use the component keyword to define reusable UI elements with Go-checked parameters and HTML-like syntax.
```gsx
import "github.com/gsxhq/gsx"
component Card(title string, featured bool, children gsx.Node) {
{ title }
{ children }
}
```
--------------------------------
### Serialize tags in GSX
Source: https://gsxhq.github.io/guide/syntax/elements.html
Illustrates how GSX serializes non-void elements to canonical HTML shapes.
```gsx
package views
component Divider() {
Content after the divider stays outside it.
}
```
```html
Content after the divider stays outside it.
```
--------------------------------
### Use default filter
Source: https://gsxhq.github.io/guide/syntax/pipelines.html
The default filter returns the first non-zero value provided.
```gsx
{count |> default(1)}
{label |> default(shortLabel, "Untitled")}
```
--------------------------------
### Configure Top-Level Class Merger
Source: https://gsxhq.github.io/guide/config.html
Define the class_merger at the top level of the configuration to ensure correct decoding.
```toml
class_merger = "example.com/app/twcfg.Merge"
[minify]
css = "full"
```