views:

1323

answers:

3

I'm doing something like:

{% extends 'base.html' %}
{% url myapp.views.dashboard object as object_url %}
{% block sidebar %}
... {{ object_url }} ...
{% endblock %}
{% block content %}
... {{ object_url }} ...
{% endblock %}

Django documentation says url templatetag can define a variable in context, but I don't get any value for object_url in the following blocks.

If I put the url templatetag at the beginning of each block, it works, but I don't want to "repeat myself".

Anyone knows a better solution?

+3  A: 

If the URL is view specific, you could pass the URL from your view. If the URL needs to be truly global in your templates, you could put it in a context processor:

def object_url(request):
    return {'object_url': reverse('myapp.views.dashboard')}
defrex
+1, you're faster than me.
TokenMacGuy
Um, many view uses this variable but not all. Also, I'm using the same pattern for another kind of variables defined by my custom templatetags. The case above is just simplified, so I think it's not appropriate to adopt your solution as it is.
Achimnol
Even if it's not used in every template it doesn't hurt anything to put it into a context processor... unless it's doing a database lookup of course, in which case it can impact site performance.
Van Gale
A: 

Well, this is kind of abusive of template inheritance, but you could use {{block.super}} to put object_url into your blocks.

In other words, in your mid-level template do:

{% block sidebar %}{{ object_url }}{% endblock %}
{% block content %}{{ object_url }}{% endblock %}

And then in your block templates use:

{% block sidebar %}
... {{ block.super }}...
{% endblock %}

It's not a great idea because it prevents you from putting anything besides {{ object_url }} into your block... but it works. Just don't tell anyone you got it from me!

Van Gale
I should add that personally I prefer being explicit and doing the load in each template. Makes it easier for me to see exactly where my data is coming from.
Van Gale
A: 

In every inherited template any code outside blocks redefinitions is not executed. So in your example you have to call {% url %} tag inside each block or use context processor for setting "global" variable.

Alex Koshelev