templ-syntax

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Templ Syntax

Templ语法

Use this skill with progressive disclosure: start at Level 1, then read deeper sections only when needed.
使用本技能时采用渐进式学习方式:从第1级开始,仅在需要时再深入阅读后续章节。

Level 1: Fast Path

第1级:快速入门路径

Use this skill when you need to write or fix
.templ
syntax.
  1. Define a component with typed params.
  2. Render values with
    { expr }
    .
  3. Compose components with
    @OtherComponent(...)
    .
  4. Use Go control flow (
    if
    ,
    for
    ,
    switch
    ) directly in markup.
  5. Keep business logic in Go helpers, not inline in templates.
templ
package components

templ Greeting(name string, isAdmin bool) {
    <h1>Hello, { name }</h1>
    if isAdmin {
        <p>Admin mode</p>
    }
}
当你需要编写或修复
.templ
语法时使用本技能。
  1. 使用带类型的参数定义组件。
  2. 使用
    { expr }
    渲染值。
  3. 使用
    @OtherComponent(...)
    组合组件。
  4. 在标记中直接使用Go的控制流(
    if
    for
    switch
    )。
  5. 将业务逻辑放在Go辅助函数中,而非内联在模板里。
templ
package components

templ Greeting(name string, isAdmin bool) {
    <h1>Hello, { name }</h1>
    if isAdmin {
        <p>Admin mode</p>
    }
}

Level 2: Core Rules

第2级:核心规则

  • Output:
    { value }
    auto-escapes text.
  • Dynamic attrs:
    class={ classes }
    ,
    disabled?={ isDisabled }
    .
  • Children: accept with
    { children... }
    , pass with block syntax.
  • Composition: call components with
    @Component(...)
    .
  • Safety: URLs should use safe helpers (for example
    templ.URL(...)
    ) when appropriate.
  • 输出:
    { value }
    会自动转义文本。
  • 动态属性:
    class={ classes }
    disabled?={ isDisabled }
  • 子元素: 使用
    { children... }
    接收,通过块语法传递。
  • 组件组合: 使用
    @Component(...)
    调用组件。
  • 安全性: 适当时应使用安全辅助函数(例如
    templ.URL(...)
    )处理URL。

Level 3: Common Patterns

第3级:常见模式

templ
templ Card(title string) {
    <section class="card">
        <h2>{ title }</h2>
        <div>{ children... }</div>
    </section>
}

templ UserList(users []string) {
    if len(users) == 0 {
        <p>No users</p>
    } else {
        <ul>
            for _, user := range users {
                <li>{ user }</li>
            }
        </ul>
    }
}
templ
templ Card(title string) {
    <section class="card">
        <h2>{ title }</h2>
        <div>{ children... }</div>
    </section>
}

templ UserList(users []string) {
    if len(users) == 0 {
        <p>No users</p>
    } else {
        <ul>
            for _, user := range users {
                <li>{ user }</li>
            }
        </ul>
    }
}

Escalate to Other Skills

关联其他技能

  • Building reusable UI APIs: use
    templ-components
    .
  • Wiring templates to handlers/routes: use
    templ-http
    .
  • Adding dynamic interactions: use
    templ-htmx
    .
  • 构建可复用UI接口:使用
    templ-components
  • 将模板与处理器/路由关联:使用
    templ-http
  • 添加动态交互:使用
    templ-htmx

References

参考资料