六维教程

Astro 条件渲染

按条件渲染元素

条件渲染指的是「根据数据决定页面上显示什么」。Astro 模板里没有独立的 if 块语法,条件输出靠以下几种写法实现。

&& 条件渲染

最简单的条件渲染是「满足才显示」,在花括号里用 && 即可。

---
const isLogin = false;
---
{isLogin && <p>欢迎回来</p>}

isLogintrue 时显示段落,否则什么都不渲染。

三元表达式

需要在两种内容之间切换时,用三元表达式。

---
const score = 85;
---
<p>评级:{score >= 60 ? '及格' : '不及格'}</p>

多分支

当分支很多时,直接在模板写层层嵌套会很乱。可以先在 frontmatter 脚本里算好结果,再渲染。

---
const score = 85;
let level = '不及格';
if (score >= 90) level = '优秀';
else if (score >= 60) level = '及格';
---
<p>评级:{level}</p>

模板没有 if 块

Astro 模板不支持像 {if (x) { ... }} 这样的 if 块写法,能用的只有 &&、三元表达式,以及上一段提到的「在 frontmatter 里先用 if/else 算好结果」。复杂条件优先放在脚本里处理,模板只负责把结果输出出来,可读性更好。

按条件控制属性

条件不仅可以控制整段 HTML,也能控制单个属性是否存在。

---
const disabled = true;
---
<button disabled={disabled}>提交</button>

disabledfalse,Astro 会自动省略这个属性,等价于不写。

留意 JS 假值陷阱

Astro 模板遵循 JavaScript 真值规则,0''falsenullundefined 都会被当作「假」,导致 && 不渲染右侧。

---
const count = 0;
---
{count && <p>有 {count} 条</p>}  // 这里会渲染出 0,不是段落

如果想在 count 为 0 时也正常显示,应改成显式比较。

{count >= 0 && <p>有 {count} 条</p>}
上一篇
Astro 组件 Props
下一篇
Astro 列表渲染