topLeft lightmiddlePinkLightrightPurpleLight

Aggiunta di dati di schema ai siti Next.js

Paul Grieselhuber

Paul Grieselhuber

Apr 25, 2019

Nello stesso spirito del post della scorsa settimana su che aggiungeva citazioni ai dati di Schema.org, questo post fornisce un metodo rapido e semplice per aggiungere dati Schema.org a un sito Next.js.

In questo progetto sto usando Apollo per prelevare i dati via GraphQL da un sito Wordpress (che finisce per generare un sito HTML statico) - quindi si presume che la struttura dei dati dei post di WP sia standard. Questo metodo presuppone che abbiate chiamato il componente Schema nel vostro componente Post (o simile) nella vostra applicazione Next.js. Quindi, richiamare il componente Schema come segue:

<Schema post={post} />

E il componente Schema stesso:

import Head from "next/head";
import { site, siteTitle } from "../../config";

function strip(html) {
  const one = html.replace(/<\/?[^>]+(>|$)/gm, "");
  const two = one.replace(/[\r\n]\s*[\r\n]/gm, "");

  return two;
}

const Schema = ({ post }) => {
  const {
    title,
    blurb,
    featuredImage,
    date,
    modified,
    slug,
    commentCount,
    author,
    ratingCount,
    ratingAverage,
    citations,
  } = post;
  const published = new Date(date);
  const copyrightYear = published.getFullYear();

  let mediaDetails, sourceUrl;

  if (featuredImage) {
    sourceUrl = featuredImage.sourceUrl;
  }

  const citationsList = citations.map((citation, i) => {
    return `{ "@type": "CreativeWork", "citation": ${JSON.stringify(
      citation
    )} }${i === citations.length - 1 ? "" : ","}\n`;
  });

  const citationsText = citationsList.join("");

  const org = `{ "@id": "${site}#organization", "type": "Organization", "name":"${siteTitle}", "logo": {
    "@type": "ImageObject",
    "name": "${siteTitle} Logo",
    "width": "230",
    "height": "67",
    "url": "${site}images/logo.png"
} }`;

  return (
    <Head>
      <script type="application/ld+json">{`
    {
      "@context":"https://schema.org/",
      "@type":"Article",
      "name":"${title}",
      ${
        ratingAverage > 4
          ? `"aggregateRating": {
        "@type":"AggregateRating",
        "ratingValue":${ratingAverage},
        "reviewCount":${ratingCount}
      },`
          : ""
      }
      "about": "${blurb}",
      "author": { "@type": "Person", "@id": "${site}author/${
        author.slug
      }", "name": "${author.name}" },
      ${
        citationsText.length
          ? `"citation": [
        ${citationsText}
      ],`
          : ""
      }
      "commentCount": ${commentCount},
      "copyrightHolder": { "@id": "${site}#organization" },
      "copyrightYear": ${copyrightYear},
      "datePublished": "${date}",
      "dateModified": "${modified}",
      "description": "${blurb}",
      "discussionUrl": "${site}articles/${slug}#comments",
      "editor": { "@id": "${site}author/${author.slug}#author" },
      "headline": "${title}",
      ${sourceUrl ? `"image": "${sourceUrl}",` : ""}
      "inLanguage": "English",
      "mainEntityOfPage": "${site}articles/${slug}",
      "publisher": { "@id": "${site}#organization" },
      "sourceOrganization": ${org},
      "url": "${site}articles/${slug}"

    }
    `}</script>
    </Head>
  );
};

export default Schema;

Si vedrà un strip function that I left in place in the example. I am trying to decide whether or not to include the post content nei dati di Schema. Se è così, questa funzione viene usata per ripulire l'HTML restituito come contenuto, in modo da poterlo includere nella risposta JSON.

Ecco una sintesi di questo snippet se avete idee su come migliorare. Le PR sono ovviamente benvenute.

Paul Grieselhuber

Paul Grieselhuber

Founder, President

Paul has extensive background in software development and product design. Currently he runs rendr.

Commenti

    Prenotate una telefonata di scoperta con i nostri esperti di prodotto.

    Il nostro team di esperti di applicazioni web e mobili sarà lieto di discutere con voi il vostro prossimo progetto.

    Prenotate una chiamata con noi 👋