using-unocss-with-templ

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Using UnoCSS with Templ

在Templ中使用UnoCSS

Integrate UnoCSS, an instant on-demand atomic CSS engine, with Go's templ templating language to build static sites with utility-first CSS.
Use this skill when setting up UnoCSS for templ projects, configuring CSS extraction from
.templ
files, or building static sites with Go and atomic CSS.
将即时按需原子化CSS引擎UnoCSS与Go的templ模板语言集成,构建实用优先的CSS静态网站。
适用场景:在templ项目中配置UnoCSS、从.templ文件中提取CSS、或是使用Go和原子化CSS构建静态网站时。

Quick Start

快速开始

1. Install Dependencies

1. 安装依赖

bash
undefined
bash
undefined

Install templ

Install templ

go install github.com/a-h/templ/cmd/templ@latest
go install github.com/a-h/templ/cmd/templ@latest

Install UnoCSS CLI

Install UnoCSS CLI

npm install -D unocss @unocss/cli
undefined
npm install -D unocss @unocss/cli
undefined

2. Create UnoCSS Config

2. 创建UnoCSS配置

ts
// uno.config.ts
import { defineConfig, presetUno } from "unocss";

export default defineConfig({
  presets: [presetUno()],
  content: {
    filesystem: ["**/*.templ"],
  },
});
ts
// uno.config.ts
import { defineConfig, presetUno } from "unocss";

export default defineConfig({
  presets: [presetUno()],
  content: {
    filesystem: ["**/*.templ"],
  },
});

3. Add Package Scripts

3. 添加包脚本

json
{
  "scripts": {
    "css:build": "unocss \"**/*.templ\" -o static/uno.css",
    "css:watch": "unocss \"**/*.templ\" -o static/uno.css --watch"
  }
}
json
{
  "scripts": {
    "css:build": "unocss \"**/*.templ\" -o static/uno.css",
    "css:watch": "unocss \"**/*.templ\" -o static/uno.css --watch"
  }
}

4. Use Classes in Templ

4. 在Templ中使用类

templ
// components/button.templ
package components

templ Button(text string) {
    <button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
        { text }
    </button>
}
templ
// components/button.templ
package components

templ Button(text string) {
    <button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
        { text }
    </button>
}

5. Include CSS in Layout

5. 在布局中引入CSS

templ
// layouts/base.templ
package layouts

templ Base(title string) {
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8"/>
            <title>{ title }</title>
            <link rel="stylesheet" href="/static/uno.css"/>
        </head>
        <body class="min-h-screen bg-gray-100">
            { children... }
        </body>
    </html>
}
templ
// layouts/base.templ
package layouts

templ Base(title string) {
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8"/>
            <title>{ title }</title>
            <link rel="stylesheet" href="/static/uno.css"/>
        </head>
        <body class="min-h-screen bg-gray-100">
            { children... }
        </body>
    </html>
}

6. Build Process

6. 构建流程

bash
undefined
bash
undefined

Development (parallel)

开发模式(并行运行)

templ generate --watch & npm run css:watch &
templ generate --watch & npm run css:watch &

Production

生产模式

templ generate npm run css:build go build -o app .
undefined
templ generate npm run css:build go build -o app .
undefined

Core Concepts

核心概念

UnoCSS Overview

UnoCSS 概述

UnoCSS is an atomic CSS engine that:
  • Generates CSS on-demand from utility class usage
  • Has no runtime overhead (build-time only)
  • Supports multiple presets (Tailwind-compatible, icons, attributify)
  • Extracts classes from any file type via CLI
UnoCSS是一款原子化CSS引擎,具备以下特性:
  • 根据工具类的使用情况按需生成CSS
  • 无运行时开销(仅在构建阶段处理)
  • 支持多种预设(兼容Tailwind、图标、属性化等)
  • 通过CLI从任意文件类型中提取类

How Extraction Works

提取机制

UnoCSS CLI scans files for utility class patterns and generates only the CSS needed:
bash
undefined
UnoCSS CLI会扫描文件中的工具类模式,仅生成所需的CSS:
bash
undefined

Scan specific patterns

扫描特定模式

unocss "components//*.templ" "pages//*.templ" -o static/uno.css
unocss "components//*.templ" "pages//*.templ" -o static/uno.css

With minification

启用压缩

unocss "**/*.templ" -o static/uno.css --minify
undefined
unocss "**/*.templ" -o static/uno.css --minify
undefined

Templ Integration

Templ 集成

Templ files use standard CSS class syntax:
templ
// Static classes
<div class="flex items-center gap-4">

// Dynamic classes (extracted if static)
<div class={ "p-4", templ.KV("bg-red-500", hasError) }>

// Conditional classes
if isActive {
    <span class="text-green-500">Active</span>
} else {
    <span class="text-gray-500">Inactive</span>
}
Templ文件使用标准CSS类语法:
templ
// 静态类
<div class="flex items-center gap-4">

// 动态类(静态部分会被提取)
<div class={ "p-4", templ.KV("bg-red-500", hasError) }>

// 条件类
if isActive {
    <span class="text-green-500">Active</span>
} else {
    <span class="text-gray-500">Inactive</span>
}

CLI Commands

CLI 命令

bash
undefined
bash
undefined

Basic usage

基础用法

unocss "**/*.templ" -o static/uno.css
unocss "**/*.templ" -o static/uno.css

Watch mode for development

开发监听模式

unocss "**/*.templ" -o static/uno.css --watch
unocss "**/*.templ" -o static/uno.css --watch

With preflights (reset styles)

包含预定义样式(重置样式)

unocss "**/*.templ" -o static/uno.css --preflights
unocss "**/*.templ" -o static/uno.css --preflights

Minified output

压缩输出

unocss "**/*.templ" -o static/uno.css --minify
unocss "**/*.templ" -o static/uno.css --minify

Custom config file

使用自定义配置文件

unocss "**/*.templ" -o static/uno.css -c uno.config.ts
undefined
unocss "**/*.templ" -o static/uno.css -c uno.config.ts
undefined

Common Patterns

常见模式

Responsive Design

响应式设计

templ
templ Card() {
    <div class="p-4 md:p-6 lg:p-8">
        <h2 class="text-lg md:text-xl lg:text-2xl">Title</h2>
    </div>
}
templ
templ Card() {
    <div class="p-4 md:p-6 lg:p-8">
        <h2 class="text-lg md:text-xl lg:text-2xl">Title</h2>
    </div>
}

Dark Mode

暗黑模式

templ
templ ThemeAwareCard() {
    <div class="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
        Content
    </div>
}
templ
templ ThemeAwareCard() {
    <div class="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
        Content
    </div>
}

State Variants

状态变体

templ
templ InteractiveButton() {
    <button class="bg-blue-500 hover:bg-blue-600 active:bg-blue-700 focus:ring-2">
        Click me
    </button>
}
templ
templ InteractiveButton() {
    <button class="bg-blue-500 hover:bg-blue-600 active:bg-blue-700 focus:ring-2">
        Click me
    </button>
}

Grid Layout

网格布局

templ
templ ProductGrid(products []Product) {
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        for _, p := range products {
            @ProductCard(p)
        }
    </div>
}
templ
templ ProductGrid(products []Product) {
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        for _, p := range products {
            @ProductCard(p)
        }
    </div>
}

Safelist for Dynamic Classes

动态类的安全列表

When classes are fully dynamic, use safelist:
ts
// uno.config.ts
export default defineConfig({
  safelist: [
    // Always include these
    "bg-red-500",
    "bg-green-500",
    "bg-blue-500",
    // Generate ranges
    ...Array.from({ length: 5 }, (_, i) => `p-${i + 1}`),
  ],
});
当类名完全动态时,使用安全列表:
ts
// uno.config.ts
export default defineConfig({
  safelist: [
    // 始终包含这些类
    "bg-red-500",
    "bg-green-500",
    "bg-blue-500",
    // 生成范围类
    ...Array.from({ length: 5 }, (_, i) => `p-${i + 1}`),
  ],
});

Reference Files

参考文件

  • Configuration: See UNO-CONFIG.md
  • Development workflow: See WORKFLOW.md
  • Presets guide: See PRESETS.md
  • 配置:查看 UNO-CONFIG.md
  • 开发工作流:查看 WORKFLOW.md
  • 预设指南:查看 PRESETS.md

Project Structure

项目结构

my-project/
├── components/
│   ├── button.templ
│   └── card.templ
├── layouts/
│   └── base.templ
├── pages/
│   └── home.templ
├── static/
│   └── uno.css          # Generated
├── uno.config.ts
├── package.json
├── go.mod
└── main.go
my-project/
├── components/
│   ├── button.templ
│   └── card.templ
├── layouts/
│   └── base.templ
├── pages/
│   └── home.templ
├── static/
│   └── uno.css          # 生成的文件
├── uno.config.ts
├── package.json
├── go.mod
└── main.go

Troubleshooting

故障排查

Classes Not Generated

类未生成

  1. Check file patterns in CLI command match your
    .templ
    files
  2. Verify
    content.filesystem
    in config includes
    .templ
  3. Use safelist for fully dynamic class names
  1. 检查CLI命令中的文件模式是否匹配你的.templ文件
  2. 验证配置中的
    content.filesystem
    是否包含.templ文件
  3. 为完全动态的类名使用安全列表

Classes Not Applied

类未生效

  1. Ensure CSS file is linked in HTML head
  2. Check browser dev tools for CSS loading
  3. Verify class names match UnoCSS syntax
  1. 确保CSS文件已在HTML头部引入
  2. 检查浏览器开发者工具中CSS是否加载成功
  3. 验证类名是否符合UnoCSS语法

Watch Mode Issues

监听模式问题

Run templ and UnoCSS watch in separate terminals or use a process manager:
bash
undefined
在单独的终端中运行templ和UnoCSS的监听命令,或使用进程管理器:
bash
undefined

Using npm-run-all

使用npm-run-all

npm install -D npm-run-all

```json
{
  "scripts": {
    "dev": "run-p dev:*",
    "dev:templ": "templ generate --watch",
    "dev:css": "unocss \"**/*.templ\" -o static/uno.css --watch",
    "dev:go": "go run ."
  }
}
npm install -D npm-run-all

```json
{
  "scripts": {
    "dev": "run-p dev:*",
    "dev:templ": "templ generate --watch",
    "dev:css": "unocss \"**/*.templ\" -o static/uno.css --watch",
    "dev:go": "go run ."
  }
}