Shop: sizes and colors for search engines, photos for link previews #37

Merged
jcoffey-dev merged 1 commits from seo/shop-pages into main 2026-10-17 07:32:20 +00:00
8 changed files with 202 additions and 18 deletions

No files matched your search

+5 -1
View File
@@ -47,7 +47,11 @@ const cardsDrawing = "1"
// look is the card style's fingerprint.
func cardPath(s *site.Site, p *site.Page, look string) string {
cc := s.Config.Cards
if !cc.On() || p.Image != "" || p.RedirectTo != "" || p.NoIndex || (p.Kind != site.KindPage && p.Kind != site.KindList) {
// A tag's page gets one only when the site wrote it a page of its own
// (content/tags/<tag>.md): an archive with a thousand tags doesn't want
// a thousand cards.
ownTerm := (p.Kind == site.KindTerm || p.Kind == site.KindTerms) && p.Source != ""
if !cc.On() || p.Image != "" || p.RedirectTo != "" || p.NoIndex || (p.Kind != site.KindPage && p.Kind != site.KindList && !ownTerm) {
return ""
}
name := strings.Trim(strings.ReplaceAll(p.Path, "/", "-"), "-")
+9
View File
@@ -16,6 +16,7 @@ import (
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
@@ -304,6 +305,14 @@ func funcs(s *site.Site, a *Assets, md *site.Markdown, icons Icons) template.Fun
"pageData": func(p *site.Page) []map[string]any { return pageData(s, p) },
// money 24 "USD" -> "$24.00": a price as people read it.
"money": money,
// price .Params.price: the amount as a plain number with two
// decimals ("24.40"), for machines (link previews); "" if it isn't one.
"price": func(v any) string {
if f, ok := amount(v); ok {
return strconv.FormatFloat(f, 'f', 2, 64)
}
return ""
},
// closed "2026-11-01": whether that day is over, in the site's time
// zone, when the site is built (a job's closing date, say).
"closed": func(v any) bool { return closed(s, v) },
+51
View File
@@ -90,3 +90,54 @@ func TestProductReviewsData(t *testing.T) {
t.Error("a product without reviews has a rating")
}
}
func TestProductGroupData(t *testing.T) {
list := &site.Page{Kind: site.KindList, Title: "Shop", Path: "/products/", Collection: "products", Params: map[string]any{"brand": "Acme"}}
tee := &site.Page{Kind: site.KindPage, Title: "Tee", Path: "/products/tee/", Collection: "products", Permalink: "https://example.org/products/tee/", Params: map[string]any{
"price": 24, "choose": "Size",
"variants": []any{
map[string]any{"group": "Red", "name": "S", "price": 24, "sku": "T-R-S"},
map[string]any{"group": "Red", "name": "XL", "price": 26.5, "sold_out": true},
},
}}
s := &site.Site{Config: &site.Config{Name: "Shop", URL: "https://example.org", Collections: map[string]site.CollectionConfig{"products": {Layout: "product"}}}, Pages: []*site.Page{list, tee}}
if d := pageData(s, list); len(d) != 0 {
t.Errorf("the shop's list page is described as %v", d)
}
d := productData(s, tee)
if d["@type"] != "ProductGroup" || d["brand"].(map[string]any)["name"] != "Acme" || d["productGroupID"] != "products/tee" {
t.Fatalf("group: %v", d)
}
if by, _ := d["variesBy"].([]any); len(by) != 2 || by[0] != "https://schema.org/size" || by[1] != "https://schema.org/color" {
t.Errorf("variesBy: %v", d["variesBy"])
}
vs, _ := d["hasVariant"].([]any)
if len(vs) != 2 {
t.Fatalf("hasVariant: %v", d["hasVariant"])
}
xl := vs[1].(map[string]any)
o := xl["offers"].(map[string]any)
if xl["name"] != "Tee (Red, XL)" || xl["size"] != "XL" || xl["color"] != "Red" || o["price"] != "26.50" || o["availability"] != "https://schema.org/OutOfStock" {
t.Errorf("variant: %v", xl)
}
if vs[0].(map[string]any)["sku"] != "T-R-S" {
t.Errorf("sku: %v", vs[0])
}
// One variant is just a product.
tee.Params["variants"] = tee.Params["variants"].([]any)[:1]
if d := productData(s, tee); d["@type"] != "Product" || d["offers"].(map[string]any)["price"] != "24.00" {
t.Errorf("one variant: %v", d)
}
}
func TestCardsForOwnTagPages(t *testing.T) {
s := &site.Site{Config: &site.Config{Name: "Shop", Cards: &site.CardsConfig{Enabled: true}}}
own := &site.Page{Kind: site.KindTerm, Path: "/tags/shirts/", Title: "Shirts", Source: "content/tags/shirts.md"}
bare := &site.Page{Kind: site.KindTerm, Path: "/tags/hats/", Title: "Hats"}
if cardPath(s, own, "x") == "" {
t.Error("a tag page with its own content file gets no card")
}
if cardPath(s, bare, "x") != "" {
t.Error("a generated tag page gets a card")
}
}
+116 -12
View File
@@ -49,7 +49,9 @@ func pageData(s *site.Site, p *site.Page) []map[string]any {
}
}
layout := p.Layout
if layout == "" && p.Collection != "" {
// A collection's layout is its pages' layout, not its list page's: the
// shop's list isn't a product.
if layout == "" && p.Collection != "" && p.Kind == site.KindPage {
layout = s.Config.Collections[p.Collection].Layout
}
switch layout {
@@ -478,18 +480,29 @@ func money(v any, currency string) string {
return n + " " + cur
}
// productData is a Product, or a ProductGroup when the product comes in
// sizes or colors: one Product per variant with its own price, SKU and
// availability, which is how search engines want variants described.
func productData(s *site.Site, p *site.Page) map[string]any {
vs := list(p.Params["variants"])
out := ldBase("Product")
if len(vs) > 1 {
out = ldBase("ProductGroup")
}
out["name"] = p.Title
out["url"] = p.Permalink
if p.Summary != "" {
out["description"] = p.Summary
}
var images []string
groupImage := map[string]string{} // a color's first photo
for _, ph := range list(p.Params["photos"]) {
m, _ := ph.(map[string]any)
if im := str(m["image"]); im != "" {
images = append(images, abs(s, im))
if g := str(m["group"]); g != "" && groupImage[g] == "" {
groupImage[g] = abs(s, im)
}
}
}
if len(images) > 0 {
@@ -498,29 +511,79 @@ func productData(s *site.Site, p *site.Page) map[string]any {
if v := str(p.Params["sku"]); v != "" {
out["sku"] = v
}
brand := map[string]any{"@type": "Brand", "name": productBrand(s, p)}
out["brand"] = brand
if f, ok := amount(p.Params["price"]); ok {
cur := strings.ToUpper(str(p.Params["currency"]))
if cur == "" {
cur = "USD"
}
avail := "https://schema.org/InStock"
if str(p.Params["sold_out"]) == "true" {
avail = "https://schema.org/OutOfStock"
offer := func(price float64, soldOut bool) map[string]any {
avail := "https://schema.org/InStock"
if soldOut {
avail = "https://schema.org/OutOfStock"
}
return map[string]any{"@type": "Offer", "price": strconv.FormatFloat(price, 'f', 2, 64), "priceCurrency": cur, "availability": avail, "url": p.Permalink}
}
out["offers"] = map[string]any{"@type": "Offer", "price": strconv.FormatFloat(f, 'f', 2, 64), "priceCurrency": cur, "availability": avail, "url": p.Permalink}
// Sizes and colors at different prices: the range, and how many.
if vs := list(p.Params["variants"]); len(vs) > 1 {
lo, hi := f, f
soldOut := str(p.Params["sold_out"]) == "true"
if len(vs) <= 1 {
out["offers"] = offer(f, soldOut)
} else {
// What the variants differ by: the choice's own name (choose:,
// "Size") and, when they come in groups, the group's
// (choose_group:, "Color"), where schema.org has a property for it.
sizeKey, groupKey := variesBy(str(p.Params["choose"])), variesBy(str(p.Params["choose_group"]))
if groupKey == "" && str(p.Params["choose_group"]) == "" {
groupKey = "color"
}
var by []any
var variants []any
grouped := false
for _, v := range vs {
m, _ := v.(map[string]any)
if pr, ok := amount(m["price"]); ok {
lo, hi = min(lo, pr), max(hi, pr)
name, group := str(m["name"]), str(m["group"])
grouped = grouped || group != ""
vp := ldBase("Product")
delete(vp, "@context")
label := name
if group != "" {
label = group + ", " + name
}
vp["name"] = p.Title + " (" + label + ")"
if sku := str(m["sku"]); sku != "" {
vp["sku"] = sku
}
if sizeKey != "" && name != "" {
vp[sizeKey] = name
}
if groupKey != "" && group != "" {
vp[groupKey] = group
}
if im := groupImage[group]; im != "" {
vp["image"] = im
} else if len(images) > 0 {
vp["image"] = images[0]
}
price := f
if pr, ok := amount(m["price"]); ok {
price = pr
}
vp["offers"] = offer(price, soldOut || str(m["sold_out"]) == "true")
variants = append(variants, vp)
}
out["offers"] = map[string]any{"@type": "AggregateOffer", "lowPrice": strconv.FormatFloat(lo, 'f', 2, 64), "highPrice": strconv.FormatFloat(hi, 'f', 2, 64), "offerCount": len(vs), "priceCurrency": cur, "availability": avail, "url": p.Permalink}
if sizeKey != "" {
by = append(by, "https://schema.org/"+sizeKey)
}
if grouped && groupKey != "" && groupKey != sizeKey {
by = append(by, "https://schema.org/"+groupKey)
}
if len(by) > 0 {
out["variesBy"] = by
}
out["productGroupID"] = productGroupID(p)
out["hasVariant"] = variants
}
}
out["brand"] = map[string]any{"@type": "Brand", "name": s.Config.Name}
// Customers' reviews of the product (the reviews pack). A business's
// reviews of itself get none: search engines ignore those.
if r := ratings(p.Params["reviews"]); r.Count > 0 {
@@ -548,6 +611,47 @@ func productData(s *site.Site, p *site.Page) map[string]any {
return out
}
// variesBy is the schema.org property for a choice's label: "Size" is
// size, "Colour" is color. Anything else has none.
func variesBy(label string) string {
switch strings.ToLower(strings.TrimSpace(label)) {
case "size", "sizes":
return "size"
case "color", "colour", "colors", "colours":
return "color"
case "material":
return "material"
case "pattern":
return "pattern"
}
return ""
}
// productBrand is the brand: the product's brand:, else its collection
// page's, else the site's name.
func productBrand(s *site.Site, p *site.Page) string {
if b := str(p.Params["brand"]); b != "" {
return b
}
if p.Collection != "" {
if l := s.PageAt(s.CollectionPath(p.Collection)); l != nil {
if b := str(l.Params["brand"]); b != "" {
return b
}
}
}
return s.Config.Name
}
// productGroupID ties a product's variants together: its sku:, else its
// address.
func productGroupID(p *site.Page) string {
if v := str(p.Params["sku"]); v != "" {
return v
}
return strings.Trim(p.Path, "/")
}
var (
mdLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`)
mdStrong = regexp.MustCompile("(\\*\\*|__|\\*|`)")
+2 -2
View File
@@ -169,7 +169,7 @@ func TestBundledPacksBuildAndPass(t *testing.T) {
{"content/picks.md", "---\ntitle: Picks\nsummary: Picks.\nsections:\n - products: { heading: Gardener's picks, tag: Garden, more: All garden things }\n---\n"},
{"content/products/print.md", "---\ntitle: Print\nsummary: A print.\nprice: 30\ncurrency: USD\nweight: 5\nvariants:\n - { group: Matte, name: A4, price: 30, buy: \"https://buy.stripe.com/a4\" }\n - { group: Matte, name: A3, price: 40, buy: \"https://buy.stripe.com/a3\", sold_out: true }\n---\n"},
}, map[string][]string{
"products/tee/index.html": {`<form class="product-form" method="get" action="https://shop.example/cart/checkout" data-cart data-field="products" data-item="{id}:{qty}" data-join="," data-title="Tee" data-href="/products/tee/" data-currency="USD" data-image="/media/a.png">`, `<input type="hidden" name="currency" value="USD">`, "<legend>Size</legend>", `name="products" value="v1:1" required data-option="S" data-cart-variant data-id="v1" data-name="S" data-price="24">`, "2XL <small>$26.00</small>", `value="v3:1" required disabled data-option="3XL" data-cart-variant`, "<span>3XL <small>sold out</small>", `data-cart-add hidden>Add to cart</button>`, `product-buy-button" type="submit">Buy now</button>`, `<script src="/hotdog-cart.`, `data-page="/cart/"`, `<a class="cart-link" href="/cart/" data-cart-link hidden>`, `<span class="product-from">From</span> $24.00`, `"@type":"AggregateOffer"`, `"lowPrice":"24.00"`, `"highPrice":"28.00"`, `"offerCount":3`},
"products/tee/index.html": {`<form class="product-form" method="get" action="https://shop.example/cart/checkout" data-cart data-field="products" data-item="{id}:{qty}" data-join="," data-title="Tee" data-href="/products/tee/" data-currency="USD" data-image="/media/a.png">`, `<input type="hidden" name="currency" value="USD">`, "<legend>Size</legend>", `name="products" value="v1:1" required data-option="S" data-cart-variant data-id="v1" data-name="S" data-price="24">`, "2XL <small>$26.00</small>", `value="v3:1" required disabled data-option="3XL" data-cart-variant`, "<span>3XL <small>sold out</small>", `data-cart-add hidden>Add to cart</button>`, `product-buy-button" type="submit">Buy now</button>`, `<script src="/hotdog-cart.`, `data-page="/cart/"`, `<a class="cart-link" href="/cart/" data-cart-link hidden>`, `<span class="product-from">From</span> $24.00`, `"@type":"ProductGroup"`, `"variesBy":["https://schema.org/size"]`, `"name":"Tee (3XL)"`, `"price":"28.00"`, "OutOfStock", `"productGroupID":"products/tee"`, `<meta property="og:type" content="product">`, `<meta property="product:price:amount" content="24.00"><meta property="product:price:currency" content="USD">`, `<meta property="og:image" content="https://example.org/media/a.png">`, `<meta property="og:image:alt" content="The tee">`},
"products/cap/index.html": {`<input type="hidden" name="products" value="c1:1" data-cart-variant data-id="c1:1" data-name="Black · One size" data-price="20">`, ">Buy now</button>"},
"cart/index.html": {`<div class="cart-view" data-cart-view data-shop="/products/">`, "The cart needs JavaScript.", `data-cart-suggest data-count="3" hidden>`, `<li class="shop-card" data-product="/products/tee/" data-tags="Garden,Shirts">`},
"privacy/index.html": {"What you put in your cart"},
@@ -179,7 +179,7 @@ func TestBundledPacksBuildAndPass(t *testing.T) {
"picks/index.html": {"Gardener&#39;s picks", `data-product="/products/tee/"`, `data-product="/products/cap/"`, `href="/tags/garden/">All garden things`},
"products/print/index.html": {`href="https://buy.stripe.com/a4" rel="noopener">Matte · A4 · $30.00`, `<span class="btn variant-sold">Matte · A3 · sold out</span>`},
"products/index.html": {`href="/products/kit/"`, "$24.00", "€12.00 · <em>Sold out</em>"},
"products/hoodie/index.html": {`<label class="variant-group" data-group-pick hidden><span>Color</span>`, `<select data-group-select data-choose="Size"><option>Red</option><option>Blue</option></select>`, `<script src="/hotdog-variants.`, `<fieldset class="variants" data-group="Blue"><legend>Blue</legend>`, `<div class="photo-slide" data-group="Blue">`, `<label class="photo-pick" data-group="Red">`},
"products/hoodie/index.html": {`<label class="variant-group" data-group-pick hidden><span>Color</span>`, `<select data-group-select data-choose="Size"><option>Red</option><option>Blue</option></select>`, `<script src="/hotdog-variants.`, `<fieldset class="variants" data-group="Blue"><legend>Blue</legend>`, `<div class="photo-slide" data-group="Blue">`, `<label class="photo-pick" data-group="Red">`, `"variesBy":["https://schema.org/size","https://schema.org/color"]`, `"color":"Blue","image":"https://example.org/media/b.png","name":"Hoodie (Blue, S)"`},
"products/kit/index.html": {`href="https://buy.stripe.com/test_1" rel="noopener">Buy`, `<div class="photo-thumbs" role="radiogroup" aria-label="Photos">`, `<label class="photo-pick"><input type="radio" name="product-photo" checked>`, "With a basket · $39.50", `alt="The card"`, `"@type":"Product"`, `"priceCurrency":"USD"`, `"price":"24.00"`, "InStock"},
"products/mug/index.html": {"Sold out", "OutOfStock"},
}},
+11
View File
@@ -305,6 +305,17 @@ func loadPage(raw []byte, rel string, md *Markdown) (*Page, error) {
p.Layout = str(fm["layout"])
p.Image = str(fm["image"])
p.ImageAlt = str(fm["image_alt"])
// A product's link preview is its first photo, not a drawn card.
if p.Image == "" {
if ph, _ := fm["photos"].([]any); len(ph) > 0 {
if m, _ := ph[0].(map[string]any); m != nil {
p.Image = str(m["image"])
if p.ImageAlt == "" {
p.ImageAlt = str(m["alt"])
}
}
}
}
p.RedirectTo = str(fm["redirect_to"])
p.Draft = truthy(fm["draft"])
p.NoIndex = truthy(fm["noindex"])
+4 -1
View File
@@ -13,7 +13,10 @@ handful of things to sell; a cart is optional (below). Card details never
touch your site,
and nothing from the provider loads until someone chooses Buy. Products are
also written as schema.org Product data, with the price and whether they're
in stock, for search engines.
in stock, for search engines; a product with sizes or colors is a
ProductGroup with one entry per variant (its own price, SKU and stock). The
brand is the product's `brand:`, else the one on `content/products/_index.md`,
else the site's name. A product's first photo is its link preview picture.
Sizes and colors are variants, each with its own price and checkout. A
provider whose checkout reads the choice from its address, as Fourthwall's
+4 -2
View File
@@ -1,7 +1,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{ $page := "" }}{{ with .Paginator }}{{ if gt .Number 1 }}{{ $page = printf " · page %d" .Number }}{{ end }}{{ end }}
{{ if .IsHome }}<title>{{ .Site.Config.Name }}</title>{{ else }}<title>{{ .Title }}{{ $page }} · {{ .Site.Config.Name }}</title>{{ end }}
{{ if .IsHome }}<title>{{ .Site.Config.Name }}{{ if and .Title (ne .Title .Site.Config.Name) }} · {{ .Title }}{{ end }}</title>{{ else }}<title>{{ .Title }}{{ $page }} · {{ .Site.Config.Name }}</title>{{ end }}
{{ $desc := default .Site.Config.Description .Summary }}
{{ with $desc }}<meta name="description" content="{{ . }}">{{ end }}
<link rel="canonical" href="{{ .Permalink }}">
@@ -12,7 +12,9 @@
<meta property="og:title" content="{{ .Title }}">
{{ with $desc }}<meta property="og:description" content="{{ . }}">{{ end }}
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:type" content="{{ if and .Collection (not .Date.IsZero) }}article{{ else }}website{{ end }}">
{{ if and (eq .Kind "page") (price .Params.price) }}<meta property="og:type" content="product">
<meta property="product:price:amount" content="{{ price .Params.price }}"><meta property="product:price:currency" content="{{ default "USD" .Params.currency | upper }}">
{{ else }}<meta property="og:type" content="{{ if and .Collection (not .Date.IsZero) }}article{{ else }}website{{ end }}">{{ end }}
{{ with .Image }}<meta property="og:image" content="{{ absURL . }}"><meta name="twitter:card" content="summary_large_image">{{ end }}
{{ with .ImageAlt }}<meta property="og:image:alt" content="{{ . }}">{{ end }}
{{ with .Site.Config.Fediverse }}<meta name="fediverse:creator" content="{{ . }}">{{ end }}