简体   繁体   中英

Django pass context from different apps to one template

I have one django project, in which several apps are registered. Each of them renders its own template, all of those extend the same basic template. Now I want to pass data to this one basic template, without having all apps do this. (Which would be quite the overhead to do) I figured doing this using custom template tags, but I am at a complete loss here, regarding possibility and how-to. Any hints or suggestions?

create a Mixin and override get_context_data() , put there all your common stuff, add this mixin to all your views that need this behaviour

class CommonMixin(object):
    def get_context_data(self, **kwargs):
        context = super(CommonMixin, self).get_context_data(**kwargs)
        context['common_value'] = 'VALUE1'
        return context


class App1View(CommonMixin, ListView):
     ...


class App2View(CommonMixin, CreateView):
    ...

if you use function view, write a function that acts as get_context_data and use it in each view.

you can create a custom tag, but is possible that this will introduce more computational cost.

Another approach can be to write a custom context processor but this will impact ALL your views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM