Astro + Contentful · Lesson 10 of 15 · 20 min
Rich text, code samples, and images
Embed reusable code samples and images inside a lesson body, render them safely, and let Contentful resize the images.
A Rich text field can hold more than paragraphs. Editors can drop other entries and assets into the middle of the text. Your code decides how each one renders.
1. Add a Code sample content type
In Content model, create Code sample. Check that its API identifier is codeSample.
| Name | Field type | Settings |
|---|---|---|
| Title | Text, short | Required. Entry title. |
| Language | Text, short | |
| Code | Text, long | Required |
Now open the Lesson content type, edit the Body field’s settings, and make sure embedded entries and embedded assets are allowed.
2. Embed one
Create and publish a Code sample entry. Something small:
<h1>Hello, Learn Hub</h1>
Open a published lesson. In the Body, put the cursor on an empty line, click Embed → Entry, and pick your code sample. Then Embed → Asset and add an image. Fill in the image’s Description. Publish everything.
3. Upgrade the renderer
Replace the file from lesson 8:
src/lib/rich-text.ts
import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
import { BLOCKS, type Document } from '@contentful/rich-text-types';
/** Make text safe to put inside HTML. */
export function escapeHtml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
/** Build an Images API URL: resized, converted to WebP. */
export function imageUrl(url: string, width: number): string {
return `https:${url}?w=${width}&fm=webp&q=75`;
}
export function richTextToHtml(doc?: Document): string {
if (!doc) return '';
return documentToHtmlString(doc, {
renderNode: {
[BLOCKS.EMBEDDED_ENTRY]: (node) => {
const entry = node.data.target;
if (entry?.sys?.contentType?.sys?.id !== 'codeSample') return '';
const { title, language, code } = entry.fields;
return `<figure class="code">
<figcaption>${escapeHtml(title ?? '')} · ${escapeHtml(language ?? 'text')}</figcaption>
<pre><code>${escapeHtml(code ?? '')}</code></pre>
</figure>`;
},
[BLOCKS.EMBEDDED_ASSET]: (node) => {
const asset = node.data.target;
const file = asset?.fields?.file;
if (!file?.contentType?.startsWith('image/')) return '';
const alt = escapeHtml(asset.fields.description ?? '');
return `<img src="${imageUrl(file.url, 800)}" alt="${alt}" loading="lazy" />`;
},
},
});
}
What each piece does
renderNode maps a kind of node to a function that returns HTML. Anything you don’t list uses the default.
node.data.target is the embedded entry or asset. It’s already filled in because the client asked for include: 2.
The content type check matters. Editors could embed any entry. You render the ones you know and skip the rest.
escapeHtml() is the security step. A code sample is full of < and >. Without escaping, the browser would run it as real HTML. The renderer escapes normal text for you. Inside your own renderNode functions, escaping is your job.
imageUrl() uses Contentful’s Images API. Add parameters to any image URL and Contentful resizes and converts it on the fly:
| Parameter | Does |
|---|---|
w=800 |
Resize to 800 pixels wide |
h=400&fit=fill |
Crop to an exact size |
fm=webp |
Convert to WebP |
q=75 |
Quality, 1 to 100 |
An editor can upload a 6 MB photo and visitors still get a small file.
4. Use it for author photos too
In the loader, swap the author photo line to use the same helper:
src/lib/contentful-loader.ts
import { imageUrl, richTextToHtml } from './rich-text';
photo: fields.photo?.fields?.file?.url
? imageUrl(fields.photo.fields.file.url, 160)
: undefined,
Add a little style for the code sample caption in BaseLayout.astro, inside the existing <style is:global>:
src/layouts/BaseLayout.astro
figure.code {
margin: 1.5rem 0;
}
figure.code figcaption {
font-size: 0.85rem;
color: #555;
}
Restart the dev server and open the lesson. The code sample shows as code, and the image loads as WebP.