#Tags

4 messages · Page 1 of 1 (latest)

frank prairie
#

I have a "blog" and a "tags" content collection. How can i reference the tags in my blog post layouts?

hollow badgeBOT
#

Hi @frank prairie. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To reference tags in your blog post layouts when using Astro content collections, you typically store the tags as an array in the frontmatter of each blog post. In your blog post layout (e.g., MarkdownPostLayout.astro), you can then access these tags via the frontmatter (or data property if using getCollection()).

Here’s how you can display and link tags in your blog post layout:

---
// Example for MarkdownPostLayout.astro
import BaseLayout from './BaseLayout.astro';
const { frontmatter } = Astro.props;
---
<BaseLayout pageTitle={frontmatter.title}>
  <p><em>{frontmatter.description}</em></p>
  <p>{frontmatter.pubDate.toString().slice(0,10)}</p>
  <p>Written by: {frontmatter.author}</p>
  <img src={frontmatter.image.url} width="300" alt={frontmatter.image.alt} />
  <div class="tags">
    {frontmatter.tags.map((tag: string) => (
      <p class="tag"><a href={`/tags/${tag}`}>{tag}</a></p>
    ))}
  </div>
  <slot />
</BaseLayout>
<style>
  a { color: #00539F; }
  .tags { display: flex; flex-wrap: wrap; }
  .tag { margin: 0.25em; border: dotted 1px #a1a1a1; border-radius: .5em; padding: .5em 1em; font-size: 1.15em; background-color: #F8FCFD; }
</style>

This approach assumes that your blog post frontmatter includes a tags array, e.g.:

---
title: "My Post"
tags: ["astro", "content collections"]
---

If you are using content collections and getCollection(), you would access tags via post.data.tags in your components. But in the layout for Markdown files, you use frontmatter.tags as shown above.

#

If you want to reference tags from a separate tags collection (for example, to get tag metadata or descriptions), you would need to use the reference() function in your collection schema to create a relationship between blog posts and tags. However, the knowledge sources do not provide a direct example of referencing a separate tags collection in the blog post layout. They do show how to reference other collections using the reference() function in the schema, and how to resolve those references using getEntry() or getEntries() in your templates, but not specifically for tags in blog layouts Defining collection references Accessing referenced data.

In summary:

  • If your tags are just arrays in frontmatter, use frontmatter.tags in your layout as above.
  • If you want to reference a separate tags collection, you need to set up references in your schema and resolve them in your template, but the knowledge sources do not provide a full example for tags specifically.

Challenge: Include tags in your blog post layout

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: