Skip to content

模板表达式参考

Astro 组件语法是 HTML 的超集。该语法旨在让任何有编写 HTML 或 JSX 经验的人都感到熟悉,并增加了对包含组件和 JavaScript 表达式的支持。

¥Astro component syntax is a superset of HTML. The syntax was designed to feel familiar to anyone with experience writing HTML or JSX, and adds support for including components and JavaScript expressions.

¥JSX-like Expressions

你可以在 Astro 组件的两个代码围栏 (---) 之间的 frontmatter 组件脚本内部定义本地 JavaScript 变量。然后,你可以使用类似 JSX 的表达式将这些变量注入到组件的 HTML 模板中!

¥You can define local JavaScript variables inside of the frontmatter component script between the two code fences (---) of an Astro component. You can then inject these variables into the component’s HTML template using JSX-like expressions!

¥Variables

可以使用大括号语法将局部变量添加到 HTML 中:

¥Local variables can be added into the HTML using the curly braces syntax:

src/components/Variables.astro
---
const name = "Astro";
---
<div>
<h1>Hello {name}!</h1> <!-- Outputs <h1>Hello Astro!</h1> -->
</div>

¥Dynamic Attributes

局部变量可以用在大括号中来将属性值传递给 HTML 元素和组件:

¥Local variables can be used in curly braces to pass attribute values to both HTML elements and components:

src/components/DynamicAttributes.astro
---
const name = "Astro";
---
<h1 class={name}>Attribute expressions are supported</h1>
<MyComponent templateLiteralNameAttribute={`MyNameIs${name}`} />

¥Dynamic HTML

局部变量可以在类似 JSX 的函数中使用来生成动态生成的 HTML 元素:

¥Local variables can be used in JSX-like functions to produce dynamically-generated HTML elements:

src/components/DynamicHtml.astro
---
const items = ["Dog", "Cat", "Platypus"];
---
<ul>
{items.map((item) => (
<li>{item}</li>
))}
</ul>

Astro 可以使用 JSX 逻辑运算符和三元表达式有条件地显示 HTML。

¥Astro can conditionally display HTML using JSX logical operators and ternary expressions.

src/components/ConditionalHtml.astro
---
const visible = true;
---
{visible && <p>Show me!</p>}
{visible ? <p>Show me!</p> : <p>Else show me!</p>}

¥Dynamic Tags

你还可以通过将 HTML 标签名称分配给变量或使用组件导入重新分配来使用动态标签:

¥You can also use dynamic tags by assigning an HTML tag name to a variable or with a component import reassignment:

src/components/DynamicTags.astro
---
import MyComponent from "./MyComponent.astro";
const Element = 'div'
const Component = MyComponent;
---
<Element>Hello!</Element> <!-- renders as <div>Hello!</div> -->
<Component /> <!-- renders as <MyComponent /> -->

使用动态标签时:

¥When using dynamic tags:

  • 变量名必须大写。例如,使用 Element,而不是 element。否则,Astro 将尝试将你的变量名称渲染为文本 HTML 标记。

  • 不支持水合指令。使用 client:* 补水指令 时,Astro 需要知道要打包哪些组件进行生产,而动态标签模式阻止了这一点。

  • 不支持 define:vars 指令。如果你无法用额外的元素(例如 <div>)封装子元素,那么你可以手动将 style={`--myVar:${value}`} 添加到你的元素中。

¥Fragments

Astro 支持 <> </> 符号,还提供内置 <Fragment /> 组件。此组件可用于在添加 set:* 指令 以注入 HTML 字符串时避免使用封装器元素。

¥Astro supports <> </> notation and also provides a built-in <Fragment /> component. This component can be useful to avoid wrapper elements when adding set:* directives to inject an HTML string.

以下示例使用 <Fragment /> 组件渲染段落文本:

¥The following example renders paragraph text using the <Fragment /> component:

src/components/SetHtml.astro
---
const htmlString = '<p>Raw HTML content</p>';
---
<Fragment set:html={htmlString} />

Astro 和 JSX 之间的差异

标题部分 Astro 和 JSX 之间的差异

¥Differences between Astro and JSX

Astro 组件语法是 HTML 的超集。它的设计初衷是让任何具有 HTML 或 JSX 经验的人都感到熟悉,但 .astro 文件和 JSX 之间存在一些关键区别。

¥Astro component syntax is a superset of HTML. It was designed to feel familiar to anyone with HTML or JSX experience, but there are a couple of key differences between .astro files and JSX.

¥Attributes

在 Astro 中,你对所有 HTML 属性使用标准 kebab-case 格式,而不是 JSX 中使用的 camelCase。这甚至适用于 React 不支持的 class

¥In Astro, you use the standard kebab-case format for all HTML attributes instead of the camelCase used in JSX. This even works for class, which is not supported by React.

example.astro
<div className="box" dataValue="3" />
<div class="box" data-value="3" />

¥Multiple Elements

Astro 组件模板可以渲染多个元素,无需将所有内容封装在单个 <div><> 中,这与 JavaScript 或 JSX 不同。

¥An Astro component template can render multiple elements with no need to wrap everything in a single <div> or <>, unlike JavaScript or JSX.

src/components/RootElements.astro
---
// Template with multiple elements
---
<p>No need to wrap elements in a single containing element.</p>
<p>Astro supports multiple root elements in a template.</p>

¥Comments

在 Astro 中,你可以使用标准 HTML 注释或 JavaScript 样式注释。

¥In Astro, you can use standard HTML comments or JavaScript-style comments.

example.astro
---
---
<!-- HTML comment syntax is valid in .astro files -->
{/* JS comment syntax is also valid */}

¥Component utilities

Astro.slots 包含用于修改 Astro 组件的带槽子组件的实用函数。

¥Astro.slots contains utility functions for modifying an Astro component’s slotted children.

类型:(slotName: string) => boolean

¥Type: (slotName: string) => boolean

你可以通过 Astro.slots.has() 检查特定插槽名称的内容是否存在。当你想要封装插槽内容但只想在使用插槽时渲染封装器元素时,这可能很有用。

¥You can check whether content for a specific slot name exists with Astro.slots.has(). This can be useful when you want to wrap slot contents but only want to render the wrapper elements when the slot is being used.

src/pages/index.astro
---
---
<slot />
{Astro.slots.has('more') && (
<aside>
<h2>More</h2>
<slot name="more" />
</aside>
)}

类型:(slotName: string, args?: any[]) => Promise<string>

¥Type: (slotName: string, args?: any[]) => Promise<string>

你可以使用 Astro.slots.render() 将槽的内容异步渲染为 HTML 字符串。

¥You can asynchronously render the contents of a slot to a string of HTML using Astro.slots.render().

---
const html = await Astro.slots.render('default');
---
<Fragment set:html={html} />

Astro.slots.render() 可选择接受第二个参数:将转发给任何子函数的参数数组。这对于自定义实用程序组件非常有用。

¥Astro.slots.render() optionally accepts a second argument: an array of parameters that will be forwarded to any function children. This can be useful for custom utility components.

例如,这个 <Shout /> 组件将其 message 属性转换为大写并将其传递到默认插槽:

¥For example, this <Shout /> component converts its message prop to uppercase and passes it to the default slot:

src/components/Shout.astro
---
const message = Astro.props.message.toUpperCase();
let html = '';
if (Astro.slots.has('default')) {
html = await Astro.slots.render('default', [message]);
}
---
<Fragment set:html={html} />

作为 <Shout /> 子级传递的回调函数将接收全大写的 message 参数:

¥A callback function passed as <Shout />’s child will receive the all-caps message parameter:

src/pages/index.astro
---
import Shout from "../components/Shout.astro";
---
<Shout message="slots!">
{(message) => <div>{message}</div>}
</Shout>
<!-- renders as <div>SLOTS!</div> -->

回调函数可以传递给带有 slot 属性的封装 HTML 元素标记内的命名插槽。此元素仅用于将回调传输到命名插槽,不会渲染到页面上。

¥Callback functions can be passed to named slots inside a wrapping HTML element tag with a slot attribute. This element is only used to transfer the callback to a named slot and will not be rendered onto the page.

<Shout message="slots!">
<fragment slot="message">
{(message) => <div>{message}</div>}
</fragment>
</Shout>

使用标准 HTML 元素作为封装标签或任何不会被解释为组件的小写标签(例如 <fragment> 而不是 <Fragment />)。请勿使用 HTML <slot> 元素,因为这将被解释为 Astro 插槽。

¥Use a standard HTML element for the wrapping tag or any lowercase tag (e.g. <fragment> instead of <Fragment />) that will not be interpreted as a component. Do not use the HTML <slot> element as this will be interpreted as an Astro slot.

Astro.self 允许递归调用 Astro 组件。此行为允许你通过在组件模板中使用 <Astro.self> 从其内部渲染 Astro 组件。这可以帮助迭代大型数据存储和嵌套数据结构。

¥Astro.self allows Astro components to be recursively called. This behavior lets you render an Astro component from within itself by using <Astro.self> in the component template. This can help iterate over large data stores and nested data structures.

NestedList.astro
---
const { items } = Astro.props;
---
<ul class="nested-list">
{items.map((item) => (
<li>
<!-- If there is a nested data-structure we render `<Astro.self>` -->
<!-- and can pass props through with the recursive call -->
{Array.isArray(item) ? (
<Astro.self items={item} />
) : (
item
)}
</li>
))}
</ul>

然后可以像这样使用该组件:

¥This component could then be used like this:

---
import NestedList from './NestedList.astro';
---
<NestedList items={['A', ['B', 'C'], 'D']} />

并且会像这样渲染 HTML:

¥And would render HTML like this:

<ul class="nested-list">
<li>A</li>
<li>
<ul class="nested-list">
<li>B</li>
<li>C</li>
</ul>
</li>
<li>D</li>
</ul>
Astro 中文网 - 粤ICP备13048890号