ibrabeicker February 2016

Django template tag modifies the context of only one block

I made a template tag with the objective of simplifying the inclusion of Angular.

The tag responsible for setting some variables in the context is the following:

@register.simple_tag(takes_context=True)
def ng_controller(context, controller_name, file_name):
    context['angular_import'] = True
    context['angular_controller_file'] = file_name
    return 'ng-controller="{}"'.format(controller_name)

the root template has this block in place of the javascript imports

{% block container_content %}{% endblock %}
{% block angular_inclusion %}{% endblock %}

the template that inherits the root template is this

{% extends 'root.html' %}
{% block container_content %}
<div class="row">
    <div class="col-sm-12">
        <div class="well" {% ng_controller 'CreateEdictController' 'js/controllers/create-edict-controller.js' %}>
            {{ angular_controller_file }}
        </div>
    </div>
</div>
{% endblock %}

{% block angular_inclusion %}
{{ angular_controller_file }}
{% endblock %}

I can successfully access {{ angular_controller_file }} in the first block, but not in the second block. How can I ensure the context manipulation affects the second block also?

Answers


Aviah Laor February 2016

Variable scope in context

Any variable set in the context will only be available in the same block of the template in which it was assigned. This behavior is intentional; it provides a scope for variables so that they don’t conflict with context in other blocks.

So the tag call in the first block container_content:

<div class="well" {% ng_controller 'CreateEdictController' 'js/controllers/create-edict-controller.js' %}>

Is ignored and missing in the second block, angular_inclusion

Post Status

Asked in February 2016
Viewed 2,046 times
Voted 4
Answered 1 times

Search




Leave an answer