1

By base.html:

{% block searchLogic %}                                
{% endblock %}                

{% block meetingDisplay %}
{% endblock %}

My index.html:

{% extends "base.html" %}

{% block searchLogic %}
{% include 'logic/anonVisitor.logic' %}
{% endblock %}

{% block meetingDisplay %}
Some html code
{% for meeting in meetings %}
{% endfor %}
{% endblock %}

My anonVisitor.logic file:

{# More code that works, I just removed it for clarity #}
{% set meetings = craft.entries.section('meetings').address(params).limit(25).order('distance').find() %}

I try to use the variable meetings in the block "meetingDisplay" in the index.html file. For some reason the variable "meetings" is no longer available.

I am trying to seperate my logic blocks and my html blocks into separate files for manageability and reuse.

All this logic worked before I broke the code and html using the extends and includes.

Is there a way to make variables set in an include be available in a block?

2

So what you're running into is Twig scoping rules, which is discussed at length in the article Twig Processing Order & Scope

The TL;DR is that a variable is only available in the context in which it is defined. Since you're setting the meetings variable in a file you included, that variable exists only in the context of the anonVisitor.logic file.

Additionally, variables defined in a parent context are available to any child templates that are included, but you can't change the values in the child templates, because you're given a copy of the context that goes away when the child templates are done rendering.

What you can do is leverage extends and embed, because templates that extends other templates have the same context as the parent that they extends.

| improve this answer | |

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.