Generating SEO title from CMS field

Hi

I’m sure I’m doing something stupid here but I’ve tried so many combinations of things I’m wondering if someone can help.

I’ve added some fields called ‘seoTitle’ and ‘metaDescription’ to my config.yml file. Here’s an example:

    collections:
  - name: service
    label: Service
    format: yml
    extension: yml
    folder: data/products/
    create: true
    slug: '{{title}}'
    fields:
      - {label: "Title", name: "title", widget: "string", required: true}
      - {label: "SEO title", name: "seoTitle", widget: "string"}
      - {label: "Meta description", name: "metaDescription", widget: "string"}
      - {label: "Publish Date", name: "date", widget: "datetime"}
      - {label: "Image", name: "image", widget: "image", required: true}
      - {label: "Body", name: "body", widget: "markdown"}

I’ve added them to all my collections and they’re showing up fine in the CMS.

I’m having referencing them in the title and meta description files though. I’ve tried doing it from a Slim file like this:


title: product.seoTitle


If I do it within the body it works fine but I can’t figure out how to reference it in the head - It just outputs ‘product.seoTitle’ as a string.

I’ve also tried doing it from my layout file:

title = current_page.seoTitle

That throws an error.

Would anyone mind suggesting what I’m doing wrong?

Looks like you’re using the Netlify CMS Middleman Starter

With yml collections in Middleman, things are a bit more complicated than using current_page.data like you would with Middleman Blog. Your page gets its data through a proxy, which looks like this:

data.products.each do |_filename, product|
  proxy "/product/#{product[:title].parameterize}/index.html", "product.html", 
  locals: {product: product}, #page data (product) is set here
  layout: 'product-detail',
  ignore: true
end

You can learn more about dynamic pages in Middleman here: https://middlemanapp.com/advanced/dynamic-pages/

In _meta.slim (or product-layout.slim if you prefer that) you can then use the data:

title = product.seoTitle

Be aware that if you use meta.slim you need a fallback for pages where the product data isn’t available, for instance blog titles or a default string.

- product = product || nil
title = product && product.seoTitle || current_page.data.title || "Default website title"

It might be easier to simplify your layout files with their own meta.

Hi Tom

I am indeed - thanks for your hard work on it.

I’ve tried setting title = product.seoTitle in both product.html.slim and meta.slim but both fail to deploy.

Could I be missing something else?

I just tested it with the blank starter and it works. Can you share your repo so I can have a look?

Apologies - I’d missed off the fallback that you mentioned. Now included and working perfectly.

Thanks for your help

2 Likes