2

私はGAE、webapp2、jinja2でプロジェクトを構築しており、承認にengineauthを使用しています。テンプレートでwebapp2.requestcontext_processorのセッション、ユーザー、その他の変数を使用するには、Djangoのようなものが必要です。この問題を解決するのを手伝ってください。

4

1 に答える 1

2

これを達成する方法はたくさんあります。

最も簡単な方法はおそらく次のようになります。

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を使用するコンテキストプロセッサ

于 2012-07-12T08:10:02.890 に答える