Originally at Include a template that sets variables (global template variables).
I have a number of templates and layouts but every layout includes a global header in which the meta data is displayed.
That data always comes from the entry you are viewing and currently I'm setting the variables the global header needs in each template, such as /news/index.html:
{% extends "_listing_layout" %}
{% set metaTitle = (entry.metaTitle) ? entry.metaTitle : entry.title %}
{% set metaDescription = entry.metaDescription %}
{% set metaKeywords = entry.metaKeywords %}
{% set metaRobots = entry.metaRobots %}
{% set openGraphImage = entry.openGraphImage.first() %}
{% if openGraphImage %}
{% set ogCrop = {
mode: 'crop',
width: 1200,
height: 630,
quality: 75,
position: 'center'
} %}
{% set openGraphImage = openGraphImage.getUrl(ogCrop) %}
{% endif %}
{% set listingSection = "newsArticles" %}
{% block content %}
<h1>{{ entry.title }}</h1>
{% include '_partials/_isotope.html' %}
{% endblock %}
The layout is super simple:
{% include '_partials/_global_header.html' %}
{% block content %}{% endblock %}
{% if craft.request.firstSegment %}
{% include '_partials/_global_footer.html' %}
{% else %}
{% include '_partials/_home_footer.html' %}
{% endif %}
And then the global header partial:
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-gb" dir="ltr" class="no-js"> <!--<![endif]-->
<head>
{# meta #}
<meta charset="utf-8">
<title>{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}</title>
{# seo #}
<meta name="description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}">
<meta name="keywords" content="{% if metaKeywords is defined %}{{ metaKeywords }}{% endif %}">
<link rel="canonical" href="{{ siteUrl }}">
<meta name="robots" content="{% if metaRobots is defined %}{{ metaRobots }}{% else %}index,follow{% endif %}">
{# open graph #}
<meta property="og:site_name" content="{{ siteName }}">
<meta property="og:type" content="website">
<meta property="og:title" content="{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}">
<meta property="og:url" content="{{ siteUrl }}">
<meta property="og:image" content="{% if openGraphImage is defined %}{{ openGraphImage }}{% else %}{{ siteUrl }}images/og-default.jpg{% endif %}">
<meta property="og:description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}">
...etc
How can I keep this variable code DRY? I've tried putting direct in the header partial and layouts, but that doesn't work. And putting it in an included partial within each template throws a template error on account of the fact the template extends a layout and can't have a body.