2

I want to create a variable based on the contents of a matrix block. This is the code I created:

{% for item in entry.screenshot %} //my matrix field
    {% for asset in item.webpage %} // an asset field in the block
        {% set backgroundUrl = asset.url %} //want to declare a variable using the asset url
   {% endfor %}
{% endfor %}

This throws a "backgroundUrl not defined" error when I try to use the variable. Obviously my syntax is wrong. Any advice would be appreciated!

| improve this question | | | | |
6

This is a twig thing. Loops in twig are scoped. Variables defined in a loop cannot be used outside of that loop. To fix this, you simply have to declare the variable before the loop:

{% set backgroundUrl = "" %}
{% for item in entry.screenshot %}
    {% for asset in item.webpage %}
        {% set backgroundUrl = asset.url %}
   {% endfor %}
{% endfor %}

If you know that you only have one asset you can shorten it a bit with:

{% set backgroundUrl = "" %}
{% for item in entry.screenshot %}
    {% set backgroundUrl = item.webpage.first().url %}
{% endfor %}
| improve this answer | | | | |
  • Thanks, Bryan Redeagle! It did seem like a scope issue, but did not know it was a Twig issue. Much appreciated! – Roi Agneta Jul 23 '14 at 21:13
  • You can shorten it even further with just this: {% set backgroundUrl = entry.screenshot[0].webpage.first().url %}. If that field is not a required field then I'd drop a conditional around it as well: this: {% set backgroundUrl = entry.screenshot | length ? entry.screenshot[0].webpage.first().url : 'no screenshot!' %} – Josh Angell Jul 24 '14 at 5:44

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.