Tassonomie

In questa pagina

Le tassonomie sono sistemi di classificazione per organizzare i contenuti. EmDash include categorie e tag integrati e supporta tassonomie personalizzate per esigenze di classificazione specializzate.

Tassonomie integrate

EmDash fornisce due tassonomie predefinite:

TassonomiaTipoDescrizione
CategorieGerarchicaClassificazione nidificata con relazioni genitore-figlio
TagPiattaEtichette semplici senza gerarchia

Entrambe sono disponibili per la collezione di post per impostazione predefinita.

Gestione dei termini

Creare un termine

Admin Dashboard

  1. Vai alla pagina della tassonomia (ad es., /_emdash/admin/taxonomies/category)

  2. Inserisci il nome del termine nel modulo Aggiungi nuovo

  3. Opzionalmente imposta:

    • Slug - Identificatore URL (generato automaticamente dal nome)
    • Genitore - Per tassonomie gerarchiche
    • Descrizione - Descrizione del termine
  4. Fai clic su Aggiungi

Content Editor

  1. Apri una voce di contenuto nell’editor

  2. Trova il pannello della tassonomia nella barra laterale

  3. Per le categorie, seleziona le caselle per i termini applicabili, o fai clic su + Aggiungi nuovo

  4. Per i tag, digita i nomi dei tag separati da virgole

  5. Salva il contenuto

API

La seguente richiesta crea un termine nella tassonomia category:

POST /_emdash/api/taxonomies/category/terms
Content-Type: application/json
Authorization: Bearer YOUR_API_TOKEN

{
  "slug": "tutorials",
  "label": "Tutorials",
  "parentId": "term_abc",
  "description": "How-to guides and tutorials"
}

Modificare un termine

  1. Vai alla pagina dei termini della tassonomia

  2. Fai clic su Modifica accanto al termine

  3. Aggiorna il nome, lo slug, il genitore o la descrizione

  4. Fai clic su Salva

Eliminare un termine

  1. Vai alla pagina dei termini della tassonomia

  2. Fai clic su Elimina accanto al termine

  3. Conferma l’eliminazione

Interrogare le tassonomie

EmDash fornisce funzioni per interrogare i termini della tassonomia e filtrare i contenuti per termine.

Ottenere tutti i termini

Recupera tutti i termini per una tassonomia:

import { getTaxonomyTerms } from "emdash";

// Get all categories (returns tree structure)
const categories = await getTaxonomyTerms("category");

// Get all tags (returns flat list)
const tags = await getTaxonomyTerms("tag");

Per le tassonomie gerarchiche, i termini includono un array children:

interface TaxonomyTerm {
	id: string;
	name: string; // Taxonomy name ("category")
	slug: string; // Term slug ("news")
	label: string; // Display label ("News")
	parentId?: string;
	description?: string;
	children: TaxonomyTerm[];
	count?: number; // Number of entries with this term
}

Ottenere un singolo termine

L’esempio seguente recupera un termine per tassonomia e slug:

import { getTerm } from "emdash";

const category = await getTerm("category", "news");
// Returns TaxonomyTerm or null

Ottenere termini per una voce

L’esempio seguente recupera le categorie e i tag assegnati a una singola voce:

import { getEntryTerms } from "emdash";

// Get all categories for a post
const categories = await getEntryTerms("posts", "post-123", "category");

// Get all tags for a post
const tags = await getEntryTerms("posts", "post-123", "tag");

Filtrare i contenuti per termine

Usa getEmDashCollection con il filtro where:

import { getEmDashCollection } from "emdash";

// Posts in the "news" category
const { entries: newsPosts } = await getEmDashCollection("posts", {
	status: "published",
	where: { category: "news" },
});

// Posts with the "javascript" tag
const { entries: jsPosts } = await getEmDashCollection("posts", {
	status: "published",
	where: { tag: "javascript" },
});

Oppure usa la funzione di convenienza:

import { getEntriesByTerm } from "emdash";

const newsPosts = await getEntriesByTerm("posts", "category", "news");

Costruire pagine di tassonomia

Archivio delle categorie

Crea una pagina che elenca i post in una categoria:

---
import { getTaxonomyTerms, getTerm, getEmDashCollection } from "emdash";
import Base from "../../layouts/Base.astro";

export async function getStaticPaths() {
  const categories = await getTaxonomyTerms("category");

  // Flatten hierarchical tree for routing
  function flatten(terms) {
    return terms.flatMap((term) => [term, ...flatten(term.children)]);
  }

  return flatten(categories).map((cat) => ({
    params: { slug: cat.slug },
    props: { category: cat },
  }));
}

const { category } = Astro.props;

const { entries: posts } = await getEmDashCollection("posts", {
  status: "published",
  where: { category: category.slug },
});
---

<Base title={category.label}>
  <h1>{category.label}</h1>
  {category.description && <p>{category.description}</p>}
  <p>{category.count} posts</p>

  <ul>
    {posts.map((post) => (
      <li>
        <a href={`/blog/${post.data.slug}`}>{post.data.title}</a>
      </li>
    ))}
  </ul>
</Base>

Archivio dei tag

Crea una pagina che elenca i post con un tag:

---
import { getTaxonomyTerms, getEmDashCollection } from "emdash";
import Base from "../../layouts/Base.astro";

export async function getStaticPaths() {
  const tags = await getTaxonomyTerms("tag");

  return tags.map((tag) => ({
    params: { slug: tag.slug },
    props: { tag },
  }));
}

const { tag } = Astro.props;

const { entries: posts } = await getEmDashCollection("posts", {
  status: "published",
  where: { tag: tag.slug },
});
---

<Base title={`Posts tagged "${tag.label}"`}>
  <h1>#{tag.label}</h1>

  <ul>
    {posts.map((post) => (
      <li>
        <a href={`/blog/${post.data.slug}`}>{post.data.title}</a>
      </li>
    ))}
  </ul>
</Base>

Widget elenco categorie

Visualizza un elenco di categorie con conteggi dei post:

---
import { getTaxonomyTerms } from "emdash";

const categories = await getTaxonomyTerms("category");
---

<nav class="category-list">
  <h3>Categories</h3>
  <ul>
    {categories.map((cat) => (
      <li>
        <a href={`/category/${cat.slug}`}>
          {cat.label} ({cat.count})
        </a>
        {cat.children.length > 0 && (
          <ul>
            {cat.children.map((child) => (
              <li>
                <a href={`/category/${child.slug}`}>
                  {child.label} ({child.count})
                </a>
              </li>
            ))}
          </ul>
        )}
      </li>
    ))}
  </ul>
</nav>

Nuvola di tag

Visualizza i tag con dimensioni basate sull’utilizzo:

---
import { getTaxonomyTerms } from "emdash";

const tags = await getTaxonomyTerms("tag");

// Calculate font sizes based on count
const counts = tags.map((t) => t.count ?? 0);
const maxCount = Math.max(...counts, 1);
const minSize = 0.8;
const maxSize = 2;

function getSize(count: number) {
  const ratio = count / maxCount;
  return minSize + ratio * (maxSize - minSize);
}
---

<div class="tag-cloud">
  {tags.map((tag) => (
    <a
      href={`/tag/${tag.slug}`}
      style={`font-size: ${getSize(tag.count ?? 0)}rem`}
    >
      {tag.label}
    </a>
  ))}
</div>

Visualizzare i termini sui contenuti

Visualizza categorie e tag su un post:

---
import { getEntryTerms } from "emdash";

interface Props {
  collection: string;
  entryId: string;
}

const { collection, entryId } = Astro.props;

const categories = await getEntryTerms(collection, entryId, "category");
const tags = await getEntryTerms(collection, entryId, "tag");
---

<div class="post-terms">
  {categories.length > 0 && (
    <div class="categories">
      <span>Posted in:</span>
      {categories.map((cat, i) => (
        <>
          {i > 0 && ", "}
          <a href={`/category/${cat.slug}`}>{cat.label}</a>
        </>
      ))}
    </div>
  )}

  {tags.length > 0 && (
    <div class="tags">
      {tags.map((tag) => (
        <a href={`/tag/${tag.slug}`} class="tag">
          #{tag.label}
        </a>
      ))}
    </div>
  )}
</div>

Tassonomie personalizzate

Crea tassonomie oltre a categorie e tag per esigenze specializzate.

Creare una tassonomia personalizzata

Usa l’API di amministrazione per creare una tassonomia:

POST /_emdash/api/taxonomies
Content-Type: application/json
Authorization: Bearer YOUR_API_TOKEN

{
  "name": "genre",
  "label": "Genres",
  "labelSingular": "Genre",
  "hierarchical": true,
  "collections": ["books", "movies"]
}

Usare tassonomie personalizzate

Interroga e visualizza le tassonomie personalizzate allo stesso modo di quelle integrate:

import { getTaxonomyTerms, getEmDashCollection } from "emdash";

// Get all genres
const genres = await getTaxonomyTerms("genre");

// Get books in a genre
const { entries: sciFiBooks } = await getEmDashCollection("books", {
	where: { genre: "science-fiction" },
});

Assegnare alle collezioni

Le tassonomie specificano a quali collezioni si applicano:

{
  "name": "difficulty",
  "label": "Difficulty Levels",
  "hierarchical": false,
  "collections": ["recipes", "tutorials"]
}

Riferimento API tassonomia

Endpoint REST

EndpointMetodoDescrizione
/_emdash/api/taxonomiesGETElenca definizioni di tassonomia
/_emdash/api/taxonomiesPOSTCrea tassonomia
/_emdash/api/taxonomies/:name/termsGETElenca termini
/_emdash/api/taxonomies/:name/termsPOSTCrea termine
/_emdash/api/taxonomies/:name/terms/:slugGETOttieni termine
/_emdash/api/taxonomies/:name/terms/:slugPUTAggiorna termine
/_emdash/api/taxonomies/:name/terms/:slugDELETEElimina termine

Assegnare termini ai contenuti

La seguente richiesta assegna termini di categoria a un post:

POST /_emdash/api/content/posts/post-123/terms/category
Content-Type: application/json
Authorization: Bearer YOUR_API_TOKEN

{
  "termIds": ["term_news", "term_featured"]
}

Prossimi passi