1👍
Answer to the 2 sub-questions:
Is there a reason why the
tag
decorator does accept thetakes_context
argument ?
It’s because, as you said, tag
is run at a lower level, parser-level of the template. There is no context at that point.
How can I access the template context with this decorator (and thus the request object) ?
I don’t think you can. Again, because it’s a parser-level thing. An interesting example is the block
tag. In order to be able to override block
tags, it uses the extend
tag to pass on some info.
I’m struggling with similar situation. The only thing I can think of is making middleware for process_request
that resets some global/singleton context which I access in tags. However this wont help if a template is rendered outside a request, like in a command.
1👍
@register.tag
takes only two arguments: the name and the compilation function. I think you can try to pass request
through the token argument in the compilation function.
UPD:
You can also access it in the Node render
method
class TestTagNode(template.Node):
def render(self, context):
return context['request'].user
@register.tag
def test_tag(parser, token):
return TestTagNode()
- [Answered ]-Django templates override: where is "Change YOUR_MODEL"
- [Answered ]-Django cache, weather site auto-refresh cache every 5 minutes
- [Answered ]-Syntax Error with Django, WSGI, and Apache