<p>Twig's <code>for</code> function is <em>scoped</em>. This means that variables defined inside of it will not be accessible outside the loop.</p>

<p>What you need to do, is to declare the variable with an initial value <em>before</em> the loop:</p>

<pre><code>{% set descr = null %}

{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr != null %}
    &lt;meta name="description" content="{{ descr }}" /&gt;
{% endif %}
</code></pre>

<p>This works, because in Twig the inner scope (i.e. your loop) will have access to variables belonging to its parent scope, but not vice versa.</p>

CC BY-SA 3.0
2015-03-12T00:40:15.743Z
2015-03-12T00:40:15.743Z
Mats Mikkel Rummelhoff
<p>quick question.</p>

<pre><code>{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr is defined %}
    &lt;meta name="description" content="{{ descr }}" /&gt;
{% endif %}
</code></pre>

<p>meta description won't show up? what am I doing wrong?</p>

<matrix>
Set Variables from the Matrix Field - SEO
# Set Variables from the Matrix Field - SEO

(Asked by: username_0 on 2015-03-11)

quick question.
{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr is defined %}
    
{% endif %}

meta description won't show up? what am I doing wrong?

**Tags:** matrix

---

## 1 answers

### Answer by username_1 on 2015-03-12. Score: 5 | Accepted answer

Twig's for function is scoped. This means that variables defined inside of it will not be accessible outside the loop.
What you need to do, is to declare the variable with an initial value before the loop:
{% set descr = null %}

{% for block in entry.matrix %}
    {% if block.type == "seo" %}
    {% set descr = block.metaDescription %}
    {% endif %}
{% endfor %}

{% if descr != null %}
    
{% endif %}

This works, because in Twig the inner scope (i.e. your loop) will have access to variables belonging to its parent scope, but not vice versa.


---

