Django templatetag scope forces me to make additional requests

The problem is that if I call templatetag in a block and it fills me with a variable with the usual context [varname] = something, then if I need this variable in another block, I have to call templatetag again. This for me means extra db queries, which are really what I'm trying to avoid.

This templatetag is called in a basic template that extends to many other templates, so I can’t just change all views to go through something in the context, it doesn’t make sense (WET principle?)

Even a context processor would not be good, because I do not want to name it for every page displayed on the site, even those that are not based on this template.

I was thinking of writing a templatetag that would use internal context structures to put a variable in a global context, but I would be too guilty of that.

How would you solve this problem?

+5
source share
4 answers

You said: "This templatetag is called in the base template, which is extended by many other templates."

The question is: is this tag called from a named block? If so then you have a couple of potential problems.

  • {% block %}pushes a new dict onto the context stack and pops it when it reaches the corresponding `{% endblock%} '. This means that any context value created while in the block substantially out of scope at the output of the block.

  • - , , , {{block.super}}, , , .

{% block %}, , , , , , , .

, , , .

, , , .

: , , ! , Django , (.. ), ( , / ) ! 2 10 . , , . , a) MonkeyPatched _resolve_lookup(), , b) curry, , , "" .

+3

, . , , , , . , , - , , , , , ? , . templatetag , ( ) .

: , , " ", . , , . , , , , : " , , , ."

+2

?

If this is the first, I would definitely go with caching. Will the caching fragment work in your case? If not, maybe you can put caching in the template tag code (assuming it's not one of the native Django templates you use)?

0
source

Just stumbled upon this trick from Liviu, Agile Bear (all credits go to him)

Instead of doing

context['some_var']='some value'

make

context.dicts[0]['some_var']='some value'

It may not be a book coding practice, but it works quite well

0
source

All Articles