Astro 组件模板语法
动态内容与逻辑
模板语法的核心,是用花括号 {} 把 JavaScript 的值写进 HTML。
花括号里写表达式
在模板里,用一对花括号 {} 可以插入任何 JavaScript 表达式的值。
---
const name = 'Astro';
const count = 3;
---
<p>欢迎使用 {name}</p>
<p>数量:{count + 1}</p>
<p>{count > 2 ? '大于2' : '不大于2'}</p>
渲染结果:
<p>欢迎使用 Astro</p>
<p>数量:4</p>
<p>大于2</p>
在模板里写逻辑
模板支持 if 和 map,写法接近 JSX 但更贴近 HTML。
---
const items = ['a', 'b', 'c'];
const show = true;
---
{show && <p>显示出来了</p>}
<ul>
{items.map((item) => <li>{item}</li>)}
</ul>
转义与原始 HTML
默认花括号里的内容会被当作文本转义。如果要插入一段已经存在的 HTML 字符串,用 set:html 指令。
---
const html = '<strong>加粗</strong>';
---
<p set:html={html} />
注意 set:html 会原样输出,不要用于不可信的用户输入,避免 XSS 风险。
属性
把动态值绑定到标签属性上,以及按条件添加属性。
动态属性
属性值也能用花括号绑定。
---
const url = '/about';
const cls = 'link';
---
<a href={url} class={cls}>关于</a>
字符串拼接时可以直接写在花括号里。
---
const id = 10;
---
<img src={`/img/${id}.png`} alt="图片" />
条件渲染属性
想「有值才加属性」,可以用展开语法。
---
const disabled = true;
const attrs = disabled ? { disabled: true } : {}; // 为空对象时,下面的展开不会添加任何属性
---
<button {...attrs}>按钮</button>
结构与注释
处理模板的包裹元素和注释写法。
注释
模板里用 HTML 注释即可,它会出现在最终 HTML 中,如果不想让注释出现在产物里,用花括号注释。
<!-- 这个注释会留在 HTML 里 -->
{/* 这个注释不会出现在产物里 */}
片段 Fragment
有时你不想多套一层 <div>,可以用 <Fragment> 包裹多个元素。
---
import Fragment from 'astro:components'; // astro:components 是 Astro 内置模块,提供 Fragment 等
---
<Fragment>
<p>第一段</p>
<p>第二段</p>
</Fragment>
实际上在 .astro 模板顶层直接并列写多个元素也是允许的,Astro 会自动处理,不需要强制包一个根节点。