1

I have a blog setup with a Categories, Archive and Tags.

In my _layout template I've been using the following to pull in SEO titles from fields, or Page/Category Titles is that's not been defined.

{% if entry is defined %}
    {% set seoTitle = entry.seoTitle %}
    {% set seoDescription = entry.seoDescription %}
    {% set seoImage = entry.seoImage %}
    {% set seoType = entry.seoType %}
    {% set title = entry.title %}
    {% set url = entry.url %}
{% endif %}


{% if category is defined %}
    {% set seoTitle = category.title %}
    {% set seoDescription = category.title %}
    {% set seoImage = category.seoImage %}
    {% set seoType = category.seoType %}
    {% set title = category.title %}
    {% set url = category.url %}
{% endif %}

<title>{{ siteName }} - {% if seoTitle is not empty %}{{ seoTitle }}{% else %}{{ title }}{% endif %}</title>
<meta name="description" content="{% if seoDescription is defined %}{{ seoDescription }}{% else %}{{ title }}{% endif %}"/>
{% if url is defined %}<link rel="home" href="{{ url }}" />{% endif %}
<meta name="twitter:card" content="summary" />
{% if url is defined %}<meta property="og:url" content="{{ url }}" />{% endif %}
<meta property="og:title" content="{% if seoTitle is not empty %}{{ seoTitle }}{% else %}{{ title }}{% endif %}" />
<meta property="og:description" content="{% if seoDescription is defined %}{{ seoDescription }}{% else %}{{ title }}{% endif %}" />
{% if seoImage is defined %}
    {% for image in seoImage %}
        <meta property="og:image" content="{{ image.getUrl()}}" />
    {% endfor %}
{% endif %}

How should I approach this for the archive and tag pages as simply doing something like the below doesn't work?

{% if tag is defined %}
{% set seoTitle = tag.title %}
....
{% endif %}
  • You could write a conditional based on the url segment if you have the tag or category visible in the url. Something like: {% if craft.request.getSegment(x) == tag.slug %} – KSPR Apr 17 '18 at 10:34
5

The better approach in my opinion is to declare the variables in the corresponding templates rather than in the _layout template

Layout.twig

{% if seoTitle is not defined or seoTitle is empty %}
    {% set seoTitle = config.seoTitle %} <-- fallback if nothing is defined
{% endif %}
<title>{{ siteName }} - {{ seoTitle }}</title>

_entry.twig

{% extends 'layout' %}
{% set seoTitle = entry.seoTitle %}

_category.twig

{% extends 'layout' %}
{% set seoTitle = category.seoTitle %}

_someOtherTemplates.twig

{% extends 'layout' %}
{% set seoTitle = 'Some hard coded strings....' %}

and so on. That way you can define seoTags based on custom properties as well otherwise it would be difficult to determinate tags on dynamic template routes without an entry or a category

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.