1

I found it pretty straightforward to get something like dynamic page titles working by setting a variable at the template level and pulling that into my site's meta tags:

My _layout.twig:

<head>
{% if title is defined %}
<title>{{ title }}</title>
{% endif %}
</head>

My template.twig:

{% set title = entry.title %}

But what's the best practice for pulling something like an asset URL that needs queried from within {% block content %}? I'm running a for loop on my asset field to grab the Url from within the template, but this doesn't seem to work outside of {% block content %}, and if I run it from within {% block content %} the variable doesn't carry over to _layout.twig where I need it in the meta tag.

My _layout.twig looks like this:

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

But how can I define an image Url that's coming from within an entry query and have it pass back to the meta tag?

3
  • Hey, can you share the code you've tried for setting the image Url? – dmatthams Nov 18 '20 at 14:46
  • @dmatthams Thanks for your comment! I was trying to set a variable (and pass it into my _layout.twig file outside of a {% block %} tag. Doing so fixed it and I added the working code I'm now using as an answer below. – Dannie Nov 18 '20 at 18:30
  • Glad you sorted it :) – dmatthams Nov 19 '20 at 9:12
2

I didn't have a full understanding of how blocks work, but I've solved my problem. I think because I was trying to set the variable in my template outside of the block (and I was trying to bring it into my _layout.twig file without referencing the block I was calling) nothing was getting properly passed from one file to the other. The solution I'm now using looks like this:

_layout.twig:

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

template.twig:

{% block ogImage %}
    {% for image in entry.eventImage.all() %}
        {{ image.url() }}
    {% endfor %}
{% endblock %}

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.