I have a site running on Jekyll and I wanted to follow the SEO best practice for the HTML page <title>
tag contents — no more than 60 characters, with the site name at the end of the title.
I started to use the truncate
Liquid filter which seems perfect for this use case. It looked like this in my head.html
include which is used on all my templates:
{%- assign meta_title = site.title -%}
{%- assign meta_title_trailer = site.title | prepend: ' | ' -%}
{%- if page.path contains '_property' -%}
{%- assign meta_title = page.title | truncate: 60, meta_title_trailer -%}
{%- elsif page.title -%}
{%- assign meta_title = page.title -%}
{%- endif -%}
The intent was this: Assign the default page title as site.title
. Then create a “trailer” version of that as well, were I prepend a pipe character and spaces around the pipe. If the page came from my Property collection, I use the page title, truncate it to the preferred 60 chars, and add the Trailer to it. The truncate
filter already accounts for the size of the 2nd parameter, so the resulting string stays at or under the desired length of 60 char.
A problem was that a short page.title
would not get truncated at all, which means it also did not get the trailer added to it. Some pages were well-formed and some we not.
Some example output:
-
First Federal Bank
— 18ch -
Ethan Allen on North Main Street in Providen... | ArtInRuins
— 60ch
I had to go about it a different way. This is what I ended up doing so that all property titles, long or short, were formed the same way:
{%- assign meta_title = site.title -%}
{%- assign meta_title_trailer = site.title | prepend: ' | ' -%}
{%- assign meta_title_truncate = 60 | minus: meta_title_trailer.size -%}
{%- if page.path contains '_property' -%}
{%- assign meta_title = page.title | truncate: meta_title_truncate | append: meta_title_trailer -%}
{%- elsif page.title -%}
{%- assign meta_title = page.title -%}
{%- endif -%}
This what is happening:
- Set the meta_title to be the
site.title
by default - Set the “trailer” to be the
site.title
prepended by a pipe and some spaces - Store the length of this string subtracted from my target length of 60
- If this is a page from the Property collection, truncate the
page.title
to my shorter length - With the truncated
page.title
, append the “trailer” - Or, if this is any other normal page with a (assumed) well formed SEO title, use that
Some example output:
-
First Federal Bank | ArtInRuins
— 31ch -
Ethan Allen on North Main Street in Providen... | ArtInRuins
— 60ch
I hope this helps someone else.