id summary reporter owner description type status component version severity resolution keywords cc stage has_patch needs_docs needs_tests needs_better_patch easy ui_ux 24694 Add support for OPTIONS['context_processors'] to Jinja2 template backend Carl Meyer Berker Peksag "Conclusion from IRC discussion: There are advantages to being explicit about request-dependence in the template (which context processors are not), but there's currently no convenient alternative to context processors for computing a non-trivial request-dependent value that you want computed only once per template render (and not at all if no template is rendered). And even if we don't like context processors as an API, they have strong precedent in Django, so people will probably find a way to use them regardless (e.g. using django-jinja instead of the built-in Jinja2 backend). They could be added as a top-level cross-backend feature, but since in 1.8 they already exist as a DTL-specific feature in `OPTIONS`, they should be added to the Jinja2 backend the same way. Full IRC discussion transcript below. It's long, but seems useful to more fully document the thinking here for posterity: {{{ mYk: I am wondering if we were wrong to not provide context processors for Jinja. IIRC the rationale was something like ""you don't need them in Jinja because you can just put stuff into the env globals directly"", but this isn't really true - the point of context processors is that they provide request-specific values, and there's no obvious way to do that. You can emulate by putting a function into the context that returns some value, but then you have inefficiency if that function does something non-trivial and its value is used in multiple places. For a concrete example, this project wants a serialized (i.e. to primitive values), JSON-serializable representation of request.user to be available in all templates. In 1.7 this was done with a context processor that provided that representation in a `me` variable. In 1.8, without some context-processor equivalent, that would have to become `me(request)` or `request|me` or something, and to avoid serializing multiple times needlessly, it would often turn into `{% set me = me(request) %}` In looking into this, I also noticed that Flask does provide context processors (just like Django's) atop Jinja2. At the moment, I'm implementing context processors for the Django Jinja2 backend. It's not hard, but unfortunately requires copying most of the implementation of the Jinja2 backend and its Template wrapper (they aren't really factored for subclass customization). I'd be very interested to hear if you think that I'm Doing it Wrong and there's a better option available for this type of use case. Or if I'm not wrong, perhaps we should consider adding support for OPTIONS['context_processors'] to the Jinja2 backend for 1.9. Or at least make it easier to subclass the backend and add that support. Specifically, this would mean factoring out an ""instantiate_template"" (name to-be-bikeshedded) internal method on the backend class, which would be called by both from_string and get_template, and which would allow a subclass to easily swap out both the Template wrapper class used and the arguments passed to it. (Actually with @jinja2.contextfunction you could remove the explicit naming of the request in the above examples, but the other issues still apply.) doesn’t django-jinja support ctx processors natively? not that it answers your questions above, just something that may buy you quicker results. So does jingo (which is what we were using on 1.7). Unfortunately jingo isn't 1.8-compatible (due to its use of template internals that changed in 1.8); do you know if django-jinja is? In any case, part of the goal of this upgrade was to switch from an external Jinja support package to the native support, so I'll probably continue on this path. Already done with adding context proc support, anyway :-) right, I think I’d like to move away from jingo in general since it does a few things oddly Thanks though! yeah, I heard django-jinja is 1.8 compatible What are you thinking of specifically? I was pretty happy with jingo as a pre-1.8 solution. django-jinja provides it's own backend class for 1.8 Ah, nice! The helpers api is clunky and the monkey patches just smell like tech debt. I don’t see why we can’t have one and only one implementation going forward now that 1.8 is out, but yeah, I get what you’re saying, it’d be neat to just move away from any library. Yeah; with 1.8 having a Jinja2 backend, I'd like to see the ""one and only implementation"" be that one. As in, if using the built-in backend is painful enough that most people are using an external library on top of it still, we should fix those pain points. so maybe we should spend more time on implementing translation support and ctx processors? yep :-) btw, I'm +1 on enabling context processors and making the backend easier to subclass I'll file an issue and PR for it, but I'd like to see if mYk has any comments first. carljm: part of the decision was: ""it's easier not to provide context processors at first and add them later than the opposite"". If Flask provides them, that's a strong argument. yes, definitely better to start minimal Flask, and it seems every third-party Django-Jinja adapter, too. it seems more straightforward to me to just add support for context processors. The question is -- should it be a ""standard"" option (like DIRS and APP_DIRS) or a ""backend-specific"" option (which goes inside OPTIONS)? Since 1.8 was released already and context_processors is a ""backend-specific"" option of the Django backend, the latter option seems less disruptive yes, that was my feeling too to be clear -- this is mostly a convenience & performance thing, right? you want to write {{ context_processor_output }} instead of {{ context_processor(request) }} in templates precisely, yes. it doesn't enable anything that is impossible otherwise. It's really the same thing you're doing with csrf_input and csrf_token in the current backend, only there you've used yet another approach (Lazy), which is one I'd dearly love to avoid :-) well I had to in that case. coming back to context processors, I really like the explicitness of {{ context_processor(request) }} yes, in that case it does have to be lazy so CSRF token isn't triggered unnecessarily - but that approach does solve the same cases I think it fits well with Django's insistence on passing the request to each view function that in itself doesn't bother me much, but for a value which may be used many places, the efficiency concern does. it also clarifies whether you can render a given template without a request (ie outside of the request-response cycle) you can do {% set somevar = context_processor(request) %}, but for ubiquitous values (the only kind I would ever use a context proc for anyway), that's ugly boilerplate to have in all templates do you often have computationally expensive things that you use multiple times in a given template?. You could also cache the value in a private attribute of the request, but that's ugly yes, I considered that, too. In the current project, I have four context processors I would use in Jinja. Only one of them (serialized user) is expensive and widely-used enough that I'd be concerned about calling it at every use site. if we step back for a minute, my general position is: * real-life usage of context processors (starting with django's built-in processors) leads me to think that they aren't a very good API * they implicitly depend on the request, which is a net negative for me, because I'm a strong proponent of dumb code * if we come up with use cases for which they're clearly the best answer, I'm happy to add them, but I'll still be afraid that they will be misused based on what you've described, I'm wondering if some sort of caching isn't a better answer to your goal: optimizing performance by avoiding repeated calls to an expensive function ...thinking... (and that will avoid paying the cost of calling that function on pages that don't use it, if any) one last idea: context processors look to me like response middleware in disguise. If you have something complicated (or expensive) to do in each response, perhaps doing it explicitly in a middleware would be a good design. Yes, that's a variant of ""cache the value in a private attribute of the request"", where the value instead becomes a public attribute of the request, attached in a middleware. I agree that solves the use case, and preserves the explicit dependence on the request. the various ideas I've suggested are merely shifting the executing of this function and the caching of its results at various points in the request/response cycle It means the value is computed for all requests, even when a template is not rendered. I'm trying to optimize for ""there should be one obvious way to do it"" and ""explicit is better than implicit"" Yes. The question is whether ""compute once when a template is rendered, and make globally available in the template context"" has enough good use cases to provide API for. it means the value is computed for all requests => maybe -- off the top of my head, I'm not sure how to tell if a given response is going to render a template My meta-concern is that it doesn't really matter whether context processors are good API; Django is stuck with them. Unless we deprecate them for DTL, the result of not providing them for Jinja may be that people just use external Jinja backends instead which provide them. yes... being technically correct serves us well if everyone keeps using django-jinja... that reminds me of mistakes I made in the time zone APIs, which were technically correct at first, and are slowly becoming usable by mortals I think for my use case (which I think is the prototypical best use case for a context processor), the best alternative would be a cached_property on the request. carljm: a realistic solution may be to provide context processors for users who are used to them and don't want to think about it, and discuss the alternatives in the docs Thus not computed unless accessed, but computed only once when accessed. Unfortunately Django makes that hard to do - trying to do the equivalent in a middleware really requires use of Lazy because you don't get to subclass Request, you just get to monkeypatch it. yup, AuthMiddleware has horrific code to set up request.user yes, horrific code which has been rewritten at least once because the previous version was both horrific and broken. I'm not taking bets on whether the current version is also horrific and broken :-) Well, my conclusion at this point is that while I see the arguments for explicit dependence on the request, I don't yet see a practical alternative to a context processor that I would be happy with for this use case. okay And given that, plus the precedent for context-processors in Django and the likelihood that people will find an implementation of them one way or another, I think I'd remain in favor of adding them. (Perhaps with discussion of downsides and alternatives in the docs.) that works for me. keeping them as a ""backend-specific"" option will also de-emphasize them a bit (even though we're just doing this because the ship has sailed with 1.8) A cached function is the closest thing to an alternative that I'd want to use, but then you have to decide between caching in a private request attr (ick) vs some other caching approach (which feels wrong because the value is logically request-scoped) sure, and in practice unless we provide a seamless convenience API for the request-scoped-cached-function approach, I don't think anyone will choose to use it over context processors. }}}" New feature closed Template system dev Normal fixed Farhan Ahmad berker.peksag@… Accepted 1 0 0 0 0 0