webapp2 jinja2 context_processor

Я создаю проект на GAE, webapp2, jinja2 и использую engineauth для авторизации. Мне нужно что-то вроде context_processor Django, чтобы использовать сеанс, пользователя и некоторые другие переменные из webapp2.request в шаблонах. Пожалуйста, помогите мне решить эту проблему.


person Daler    schedule 12.07.2012    source источник


Ответы (1)


Есть много способов добиться этого.

Самый простой способ, вероятно, выглядит так:

def extra_context(handler, context=None):
    """
    Adds extra context.
    """

    context = context or {}

    # You can load and run various template processors from settings like Django does.
    # I don't do this in my projects because I'm not building yet another framework
    # so I like to keep it simple:

    return dict({'request': handler.request}, **context)


# --- somewhere in response handler ---
def get(self):
    my_context = {}
    template = get_template_somehow()
    self.response.out.write(template.render(**extra_context(self, my_context))

Мне нравится, когда мои переменные находятся в глобальных переменных шаблона, тогда я могу получить к ним доступ в своих виджетах шаблона без необходимости передавать кучу переменных в шаблоне. Итак, я делаю это так:

def get_template_globals(handler):
    return {
        'request': handler.request,
        'settings': <...>
    }


class MyHandlerBase(webapp.RequestHandler):
    def render(self, context=None):
        context = context or {}
        globals_ = get_template_globals(self)
        template = jinja_env.get_template(template_name, globals=globals_)
        self.response.out.write(template.render(**context))

Существуют и другие методы: контекстный процессор с использованием Werkzeug и Jinja2

person Ski    schedule 12.07.2012