Django template and the locals trick

后端 未结 8 1404
不思量自难忘°
不思量自难忘° 2020-12-02 10:43

The django books gives the local trick in order to avoid to type a long list of parameters as context dictionnary

http://www.djangobook.com/en/2.0/chapter04/

8条回答
  •  遥遥无期
    2020-12-02 10:52

    To reduce clutter in views.py while keeping things explicit: In controllers.py:

    import sys
    
    def auto_context(the_locals=None):
        # Take any variable in the locals() whose name ends with an underscore, and
        # put it in a dictionary with the underscore removed.
    
        if the_locals is None:
            # We can access the locals of the caller function even if they
            # aren't passed in.
            caller = sys._getframe(1)
            the_locals = caller.f_locals
    
        return dict([
            (key[:-1], value)
            for (key, value) in the_locals.items()
            if key[-1] == "_"])
    

    In views.py:

    from app.controllers import auto_context
    
    def a_view(request): 
        hello_ = "World" # This will go into the context.
        goodnight = "Moon" # This won't.
        return render(request, "template.html", auto_context())
    

    In template.html, use {{ hello }}.

    You're unlikely to give a variable a name ending in an underscore accidentally. So you'll know exactly what's going into the template. Use auto_context() or equivalently auto_context(locals()). Enjoy!

提交回复
热议问题