<p>What you're trying to do is how I used to do it; for your specific case, I'd suggest trying out <a href="https://github.com/nystudio107/seomatic" rel="nofollow">SEOmatic</a>, which will keep all of this out of your templates, but still give you the control you want.  It will also give you a ton of meta and functionality that you're missing.</p>

<p>Now in terms of solving the generalized case of how to do this via templates, some pretty good examples have already been given.  I'd also suggest looking into the Twig <a href="http://twig.sensiolabs.org/doc/tags/embed.html" rel="nofollow">Embed</a> functionality as well.</p>

CC BY-SA 3.0
2016-07-20T02:41:09.023Z
2016-07-20T02:41:09.023Z
andrew.welch
<p>I'm doing a very similar thing. This is the approach I got to work:</p>

<p><code>_base_template.html</code>:</p>

<pre><code>{# set default vars here ... this could also be put in an include file to share across different base templates #}
{% set title_default = title_default ? title_default : 'This is the default title' %}
{% set meta_desc_default = meta_desc_default ? meta_desc_default : 'This is the default meta description' %}
{% set meta_keywords_default = meta_keywords_default ? meta_keywords_default : 'These,are,the,default,meta,keywords' %}

{# page_info is set from the CMS ... #}
&lt;title&gt;{{ page_info.page_title | default(title_default) ~ " | #{company_name}" }}&lt;/title&gt;

&lt;body&gt;
{% block content %}
{% endblock content %}
{# etc. #}
&lt;/body&gt;
</code></pre>

<p><code>child_page.html</code>:</p>

<pre><code>{% extends "_base_template.html" %}

{# only set the ones we need to override here #}
{% set title_default = 'This is the child page title.' %}

{% block content %}
{# etc. #}
{% endblock content %}
</code></pre>

<p>The key, for me, was in using the conditionals when setting the default variables. </p>

<p>What appears to happen, for me, is that it processes the <code>set</code> blocks in the child template first, and then the ones in the base template.  So without the conditionals, the defaults in the base template end up overriding the page-specific ones I set in the child page.</p>

<p>The conditionals allow me to only set the defaults if they're not already "overridden" in the child page (so to speak).</p>

<p>They could also be written in non-ternary form, which might make them easier to read, but take up more lines:</p>

<pre><code>{% if not title_default %}{% set title_default = 'This is the default title!!' %}{% endif %}
</code></pre>

<p>or:</p>

<pre><code>{% if title_default is not defined %}{% set title_default = 'This is the default title!!' %}{% endif %}
</code></pre>

<p>It's more work than using, say, PHP, but it's better than repeating all that logic on every child page.  </p>

<p>At some point, one may question whether it's better to move something like this up to the PHP level (or whatever one is using), more on the level of the "controller" than the "view".  But it still might make sense to do this on the view level.  And in some instances, maybe one doesn't have access further up the chain, before Perch gets called. </p>

<p>For the record, I'm using Twig 1.14.0 with a home-grown CMS, without CraftCMS.</p>

CC BY-SA 3.0
2016-07-20T00:56:29.190Z
2016-07-20T00:56:29.190Z
Aaron Wallentine
<p>There are two basic issues with using includes in this scenario, both of which you have discovered.</p>

<p>The first is that included templates do not have access to variables defined in master templates. You would have to specifically pass the variables to the template in the include statement using the <code>with</code> clause.</p>

<p>The second is that extended templates cannot have a body outside of a declaration block, and includes are by definition expected to return html, and thus throw an error.</p>

<p>A better solution would be to use hierarchical extensions vs includes, placing all shared content together in the parent template. All variables in child templates should bubble up through the template hierarchy and be available to the parent templates. Something like the following for example (I've left out much of the content for brevity).</p>

<p>In <code>_layout.html</code>:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;!--[if lt IE 7]&gt;      &lt;html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"&gt; &lt;![endif]--&gt;
&lt;!--[if IE 7]&gt;         &lt;html class="no-js lt-ie9 lt-ie8" lang="en"&gt; &lt;![endif]--&gt;
&lt;!--[if IE 8]&gt;         &lt;html class="no-js lt-ie9" lang="en"&gt; &lt;![endif]--&gt;
&lt;!--[if gt IE 8]&gt;&lt;!--&gt; &lt;html lang="en-gb" dir="ltr" class="no-js"&gt; &lt;!--&lt;![endif]--&gt;

&lt;head&gt;
    {# meta #}
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}&lt;/title&gt;

    {# set seo #}
    &lt;meta name="description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}"&gt;
    &lt;meta name="keywords" content="{% if metaKeywords is defined %}{{ metaKeywords }}{% endif %}"&gt;
    &lt;link rel="canonical" href="{{ siteUrl }}"&gt;
    &lt;meta name="robots" content="{% if metaRobots is defined %}{{ metaRobots }}{% else %}index,follow{% endif %}"&gt;

    {# set open graph #}
    &lt;meta property="og:site_name" content="{{ siteName }}"&gt;
    &lt;meta property="og:type" content="website"&gt;
    &lt;meta property="og:title" content="{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}"&gt;
    &lt;meta property="og:url" content="{{ siteUrl }}"&gt;
    &lt;meta property="og:image" content="{% if openGraphImage is defined %}{{ openGraphImage }}{% else %}{{ siteUrl }}images/og-default.jpg{% endif %}"&gt;
    &lt;meta property="og:description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}"&gt;

    ...etc

    {# set default site meta variables, if any #}

    {% block head %}{% endblock %}

&lt;/head&gt;    

&lt;body&gt;

    {% block content %}{% endblock %}

    {% block footer %}{% endblock %}

&lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>In <code>_home-layout.html</code>:</p>

<pre><code>{% extends "_layout" %}

{% block head %}
    {# additional home head content #}
{% endblock %}

{% block content %}{% endblock %}

{% block footer %}
    {# home footer content #}
{% endblock %}
</code></pre>

<p>In <code>_page-layout.html</code>:</p>

<pre><code>{% extends "_layout" %}

{% block head %}
    {# additional page head content #}
{% endblock %}

{% block content %}{% endblock %}

{% block footer %}
    {# page footer content #}
{% endblock %}
</code></pre>

<p>In your <code>index.html</code> template:</p>

<pre><code>{% extends "_home-layout" %}

{# set home meta variables, etc #}

{% block content %}
    {# home body content #}
{% endblock %}
</code></pre>

<p>In your <code>page.html</code> template:</p>

<pre><code>{% extends "_page-layout" %}

{# set page meta variables, etc #}

{% block content %}
    {# page body content #}
{% endblock %}
</code></pre>

<p>In this way you can group shared content in the parent template and specific content further down the template hierarchy. How best to structure this hierarchy to keep you code 'dry' will be heavily dependent on the needs of your project so I won't even begin to guess.</p>

<p>Keep in mind it is also possible to define blocks of html in variables using conditionals and then place those variables into the block declarations.</p>

<pre><code>{% if craft.request.firstSegment %}

    {% set footer %}
        {# page footer content #}
    {% endset %}

{% else %}

    {% set footer %}
        {# home footer content #}
    {% endset %}

{% endif %}

{% block footer %}
    {{ footer }}
{% endblock %}
</code></pre>

CC BY-SA 3.0
2014-12-29T22:06:47.037Z
Thanks, but I don't see how that helps. You would still have to repeat the block of code that sets each meta variable in each template. If you look at my question you can see there are 10-20 lines of code there - it's this snippet of code I'm trying to make DRY. In ExpressionEngine that would be a snippet, but I don't see how we can tackle that in Craft.
Russ Back
CC BY-SA 3.0
2014-12-29T23:43:47.393Z
Put it in an intermediary template, that is shared by all sub templates. That was the point. You should only ever have to define something once if done correctly. In my example I have the meta info set in the child template because I thought this is unique, but if it's not then move it to the parent template.
Douglas McDonald
CC BY-SA 3.0
2014-12-29T19:26:50.433Z
2015-01-05T19:35:04.120Z
2015-01-05T19:35:04.120Z
Douglas McDonald
<p>Originally at <a href="https://craftcms.stackexchange.com/questions/5313/include-a-template-that-sets-variables-global-template-variables/5318?noredirect=1#comment6287_5318">Include a template that sets variables (global template variables)</a>.</p>

<p>I have a number of templates and layouts but every layout includes a global header in which the meta data is displayed. </p>

<p>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:</p>

<pre><code>{% 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 %}

    &lt;h1&gt;{{ entry.title }}&lt;/h1&gt;

    {% include '_partials/_isotope.html' %}

{% endblock %}
</code></pre>

<p>The layout is super simple:</p>

<pre><code>{% include '_partials/_global_header.html' %}

    {% block content %}{% endblock %}

{% if craft.request.firstSegment %}

    {% include '_partials/_global_footer.html' %}

{% else %}

    {% include '_partials/_home_footer.html' %}

{% endif %}
</code></pre>

<p>And then the global header partial:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;!--[if lt IE 7]&gt;      &lt;html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"&gt; &lt;![endif]--&gt;
&lt;!--[if IE 7]&gt;         &lt;html class="no-js lt-ie9 lt-ie8" lang="en"&gt; &lt;![endif]--&gt;
&lt;!--[if IE 8]&gt;         &lt;html class="no-js lt-ie9" lang="en"&gt; &lt;![endif]--&gt;
&lt;!--[if gt IE 8]&gt;&lt;!--&gt; &lt;html lang="en-gb" dir="ltr" class="no-js"&gt; &lt;!--&lt;![endif]--&gt;

    &lt;head&gt;

        {# meta #}
        &lt;meta charset="utf-8"&gt;
        &lt;title&gt;{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}&lt;/title&gt;

        {# seo #}
        &lt;meta name="description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}"&gt;
        &lt;meta name="keywords" content="{% if metaKeywords is defined %}{{ metaKeywords }}{% endif %}"&gt;
        &lt;link rel="canonical" href="{{ siteUrl }}"&gt;
        &lt;meta name="robots" content="{% if metaRobots is defined %}{{ metaRobots }}{% else %}index,follow{% endif %}"&gt;

        {# open graph #}
        &lt;meta property="og:site_name" content="{{ siteName }}"&gt;
        &lt;meta property="og:type" content="website"&gt;
        &lt;meta property="og:title" content="{% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}"&gt;
        &lt;meta property="og:url" content="{{ siteUrl }}"&gt;
        &lt;meta property="og:image" content="{% if openGraphImage is defined %}{{ openGraphImage }}{% else %}{{ siteUrl }}images/og-default.jpg{% endif %}"&gt;
        &lt;meta property="og:description" content="{% if metaDescription is defined %}{{ metaDescription }}{% endif %}"&gt;

...etc
</code></pre>

<p>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.</p>

<templating><variable>
How can I globally set variables?
# How can I globally set variables?

(Asked by: username_0 on 2014-12-24)

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 %}

    {{ entry.title }}

    {% 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:




  

    

        {# meta #}
        
        {% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}

        {# seo #}
        
        
        
        

        {# open graph #}
        
        
        
        
        
        

...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.

**Tags:** templating, variable

---

## 3 answers

### Answer by username_3 on 2014-12-29. Score: 4 | Accepted answer

There are two basic issues with using includes in this scenario, both of which you have discovered.
The first is that included templates do not have access to variables defined in master templates. You would have to specifically pass the variables to the template in the include statement using the with clause.
The second is that extended templates cannot have a body outside of a declaration block, and includes are by definition expected to return html, and thus throw an error.
A better solution would be to use hierarchical extensions vs includes, placing all shared content together in the parent template. All variables in child templates should bubble up through the template hierarchy and be available to the parent templates. Something like the following for example (I've left out much of the content for brevity).
In _layout.html:




  


    {# meta #}
    
    {% if metaTitle is defined %}{{ metaTitle }} - {% endif %}{{ siteName }}

    {# set seo #}
    
    
    
    

    {# set open graph #}
    
    
    
    
    
    

    ...etc

    {# set default site meta variables, if any #}

    {% block head %}{% endblock %}

    



    {% block content %}{% endblock %}

    {% block footer %}{% endblock %}





In _home-layout.html:
{% extends "_layout" %}

{% block head %}
    {# additional home head content #}
{% endblock %}

{% block content %}{% endblock %}

{% block footer %}
    {# home footer content #}
{% endblock %}

In _page-layout.html:
{% extends "_layout" %}

{% block head %}
    {# additional page head content #}
{% endblock %}

{% block content %}{% endblock %}

{% block footer %}
    {# page footer content #}
{% endblock %}

In your index.html template:
{% extends "_home-layout" %}

{# set home meta variables, etc #}

{% block content %}
    {# home body content #}
{% endblock %}

In your page.html template:
{% extends "_page-layout" %}

{# set page meta variables, etc #}

{% block content %}
    {# page body content #}
{% endblock %}

In this way you can group shared content in the parent template and specific content further down the template hierarchy. How best to structure this hierarchy to keep you code 'dry' will be heavily dependent on the needs of your project so I won't even begin to guess.
Keep in mind it is also possible to define blocks of html in variables using conditionals and then place those variables into the block declarations.
{% if craft.request.firstSegment %}

    {% set footer %}
        {# page footer content #}
    {% endset %}

{% else %}

    {% set footer %}
        {# home footer content #}
    {% endset %}

{% endif %}

{% block footer %}
    {{ footer }}
{% endblock %}

> **Comments:**
> **username_0**: Thanks, but I don't see how that helps. You would still have to repeat the block of code that sets each meta variable in each template. If you look at my question you can see there are 10-20 lines of code there - it's this snippet of code I'm trying to make DRY. In ExpressionEngine that would be a snippet, but I don't see how we can tackle that in Craft.  
> **username_3**: Put it in an intermediary template, that is shared by all sub templates. That was the point. You should only ever have to define something once if done correctly. In my example I have the meta info set in the child template because I thought this is unique, but if it's not then move it to the parent template.  

---

### Answer by username_1 on 2016-07-20. Score: 2

What you're trying to do is how I used to do it; for your specific case, I'd suggest trying out [SEOmatic](https://github.com/nystudio107/seomatic), which will keep all of this out of your templates, but still give you the control you want. It will also give you a ton of meta and functionality that you're missing.

Now in terms of solving the generalized case of how to do this via templates, some pretty good examples have already been given. I'd also suggest looking into the Twig [Embed](http://twig.sensiolabs.org/doc/tags/embed.html) functionality as well.


---

### Answer by username_2 on 2016-07-20. Score: 1

I'm doing a very similar thing. This is the approach I got to work:
_base_template.html:
{# set default vars here ... this could also be put in an include file to share across different base templates #}
{% set title_default = title_default ? title_default : 'This is the default title' %}
{% set meta_desc_default = meta_desc_default ? meta_desc_default : 'This is the default meta description' %}
{% set meta_keywords_default = meta_keywords_default ? meta_keywords_default : 'These,are,the,default,meta,keywords' %}

{# page_info is set from the CMS ... #}
{{ page_info.page_title | default(title_default) ~ " | #{company_name}" }}


{% block content %}
{% endblock content %}
{# etc. #}


child_page.html:
{% extends "_base_template.html" %}

{# only set the ones we need to override here #}
{% set title_default = 'This is the child page title.' %}

{% block content %}
{# etc. #}
{% endblock content %}

The key, for me, was in using the conditionals when setting the default variables. 
What appears to happen, for me, is that it processes the set blocks in the child template first, and then the ones in the base template.  So without the conditionals, the defaults in the base template end up overriding the page-specific ones I set in the child page.
The conditionals allow me to only set the defaults if they're not already "overridden" in the child page (so to speak).
They could also be written in non-ternary form, which might make them easier to read, but take up more lines:
{% if not title_default %}{% set title_default = 'This is the default title!!' %}{% endif %}

or:
{% if title_default is not defined %}{% set title_default = 'This is the default title!!' %}{% endif %}

It's more work than using, say, PHP, but it's better than repeating all that logic on every child page.  
At some point, one may question whether it's better to move something like this up to the PHP level (or whatever one is using), more on the level of the "controller" than the "view".  But it still might make sense to do this on the view level.  And in some instances, maybe one doesn't have access further up the chain, before Perch gets called. 
For the record, I'm using Twig 1.14.0 with a home-grown CMS, without CraftCMS.


---

