1

I have the following code in the “main.twig” template:

<head>
    {% block head %}
        <meta property="og:image" content="{% block pageImage %}{% endblock %}" />
    {% endblock %}
</head>

Then, I’m trying to populate the image URL into the < meta > tag from a Matrix field:

{% extends "templates/main" %}
{% for block in entry.articleBody %}
    {% if block.type == "articleImage" %}
        {% set image = block.articleImage.first().getUrl() %}
        {% block pageImage %}{{ image }}{% endblock %}
    {% endif %}
{% endfor %}
{% block head %}{{ parent() }}{% endblock %}

However, no URL is outputted. Does anyone know why?

Thanks!

4

Twig generally doesn't like nested/un-nested blocks like this. A better way to deal with this would be to just set a variable; and since twig renders templates from the inside-out, any variables that you define in child-templates should be available to the parent.

So in 'main.twig':

<head>
    <meta property="og:image" content="{% if seoImage is defined %}{{ seoImage }}{% endif %}" />
</head>

And in your child-template:

{% extends "templates/main" %}

{# note: needs to be defined outside the 'for' loop to become available #}
{% set seoImage="" %} 
{% for block in entry.articleBody %}
    {% if block.type == "articleImage" %}
        {% set seoImage = block.articleImage.first().getUrl() %}
    {% endif %}
{% endfor %}

You can still use blocks of course in addition to this technique, but generally best to keep them in the same nesting order.

On a side-note: I don't think you need the 'templates/' part of the extends statement (unless you have a 'templates' folder inside 'templates'). Normally you would just use {% extends "_main" %}. The underscore in the name also prevents the template from being loaded directly.

| improve this answer | |
  • Also, yes, I do have a ‘templates’ folder inside ‘craft/templates’—a bit confusing, but helps me distinguish templates called by Routing from child templates, which I put into a separate ‘includes’ folder. – Martin Adams Apr 26 '15 at 19:07
  • That did it! Thank you, Douglas! I also didn’t know I had to define the variable first {% set seoImage="" %} before assigning it a value! Much appreciated. – Martin Adams Apr 26 '15 at 19:16

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.