Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update API Reference #291

Merged
merged 4 commits into from
Apr 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 103 additions & 49 deletions src/pages/en/reference/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,79 +7,102 @@ title: API Reference

The `Astro` global is available in all contexts in `.astro` files. It has the following functions:

### `Astro.fetchContent()`
### `Astro.glob()`

`Astro.fetchContent()` is a way to load local `*.md` files into your static site setup.
`Astro.glob()` is a way to load many local files into your static site setup.

```astro
---
// ./src/components/my-component.astro
const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
const posts = await Astro.glob('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
---

<div>
{data.slice(0, 3).map((post) => (
{posts.slice(0, 3).map((post) => (
<article>
<h1>{post.title}</h1>
<p>{post.description}</p>
<a href={post.url}>Read more</a>
<h1>{post.frontmatter.title}</h1>
<p>{post.frontmatter.description}</p>
<a href={post.frontmatter.url}>Read more</a>
</article>
))}
</div>
```

`.fetchContent()` only takes one parameter: a relative URL glob of which local files you'd like to import. Currently only `*.md` files are supported. It’s synchronous, and returns an array of items of type:
`.glob()` only takes one parameter: a relative URL glob of which local files you'd like to import. It’s asynchronous, and returns an array of the exports from matching files.

```js
{
/* frontmatter from the post

example:
{
title: '',
tag: '',
date: '',
image: '',
author: '',
description: '',
}
*/
astro: {
headers: [], // an array of h1...h6 elements in the markdown file
source: '', // raw source of the markdown file
html: '', // rendered HTML of the markdown file
},
url: '', // the rendered path
}[]
#### Markdown Files

Markdown files have the following interface:

```ts
export interface MarkdownInstance<T extends Record<string, any>> {
/* Any data specified in this file's YAML frontmatter */
frontmatter: T;
/* The file path of this file */
file: string;
/* The rendered path of this file */
url: string | undefined;
/* Astro Component that renders the contents of this file */
Content: AstroComponent;
/* Function that returns array of h1...h6 element in this file */
getHeaders(): Promise<{ depth: number; slug: string; text: string }[]>;
}
```

### `Astro.request`
You can optionally provide a type for the `frontmatter` variable using a TypeScript generic.

`Astro.request` returns an object with the following properties:
```astro
---
interface Frontmatter {
title: string;
description?: string;
}
const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');
---

| Name | Type | Description |
| :------------- | :---- | :---------------------------------------------- |
| `url` | `URL` | The URL of the request being rendered. |
| `canonicalURL` | `URL` | [Canonical URL][canonical] of the current page. |
<ul>
{posts.map(post => <li>{post.title}</li>)}
</ul>
```

### `Astro.resolve()`
#### Astro Files

> ⚠️ This feature is in the process of being **deprecated**. Please review the [migration guide](/en/migrate#deprecated-astroresolve) to upgrade your asset references to a future-proof option.
Astro files have the following interface:

`Astro.resolve()` helps with creating URLs relative to the current Astro file, allowing you to reference files within your `src/` folder.
```ts
export interface AstroInstance {
default: AstroComponent;
}
```

Astro _does not_ resolve relative links within HTML, such as images:
#### Other Files

```html
<img src="../images/penguin.png" />
Other files may have various different interfaces, but `Astro.glob()` accepts a TypeScript generic if you know exactly what an unrecognized file type contains.

```ts
---
interface CustomDataFile {
default: Record<string, any>;
}
const data = await Astro.glob<CustomFile>('../data/**/*.js');
---
```

The above will be sent to the browser as-is and the browser will resolve it relative to the current **page**. If you want it to be resolved relative to the .astro file you are working in, use `Astro.resolve`:
### `Astro.request`

`Astro.request` is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. It can be used to get the `url`, `headers`, `method`, and even body of the request. Use `new URL(Astro.request.url)` to get a URL object.

```astro
<img src={Astro.resolve('../images/penguin.png')} />
---
const url = new URL(Astro.request.url);
---
<h1>Origin {url.origin}</h1>
```

### `Astro.canonicalURL`

The [canonical URL][canonical] of the current page. If the `site` option is set, the site's origin will be the origin of this URL.

### `Astro.site`

`Astro.site` returns a `URL` made from `buildOptions.site` in your Astro config. If undefined, this will return a URL generated from `localhost`.
Expand All @@ -94,15 +117,46 @@ const path = Astro.site.pathname;

### `Astro.slots`

`Astro.slots` returns an object with any slotted regions passed into the current Astro file.
`Astro.slots` contains utility functions for modifying an Astro component's slotted children.

```js
const {
heading as headingSlot, // true or undefined, based on whether `<* slot="heading">` was used.
default as defaultSlot, // true or undefined, based on whether `<* slot>` or `<* default>` was used.
} = Astro.slots;
| Name | Type | Description |
| :------------- | :------------------------------------------------ | :------------------------------------------------- |
| `has` | `(name: string) => boolean` | Whether content for this slot name exists |
| `render` | `(name: string, args?: any[]) => Promise<string>` | Asychronously renders this slot and returns HTML |

```astro
---
let html: string = '';
if (Astro.slots.has('default')) {
html = await Astro.slots.render('default')
}
---
<Fragment set:html={html} />
```

`Astro.slots.render` optionally accepts a second argument, an array of parameters that will be forwarded to any function children. This is extremely useful for custom utility components.

Given the following `Message.astro` component...

```astro
---
let html: string = '';
if (Astro.slots.has('default')) {
html = await Astro.slots.render('default', Astro.props.messages)
}
---
<Fragment set:html={html} />
```

You could pass a callback function that renders our the message:

```astro
<div><Message messages={['Hello', 'world!']}>{(messages) => messages.join(' ')}</Message></div>
<!-- renders as -->
<div>Hello world!</div>
```


## `getStaticPaths()`

If a page uses dynamic params in the filename, that component will need to export a `getStaticPaths()` function.
Expand Down