2015-03-31 30 views
3

我正在編寫自定義jinja2 extension以便在flask應用程序中使用,我正在尋找一種方法來使用我正在實施的標記來訪問模板上下文數據。也就是說,我想使用的上下文的擴展標籤PARAMS傳遞到模板:定製jinja2標籤如何與燒瓶請求的上下文接口

@app.route('/users/<user_id>') 
def user_page(user_id): 
    ... 
    return render_template('users/index.html', user_id=user_id, active=True) 

模板:

<!-- I want this tag to see the value of user_id and active --> 
{% my_jinja2_tag %} 

我知道我可以用渲染的{{ user_id }}上下文變量,但我什麼尋找是一種方法來檢查模板渲染自定義jinja2擴展的上下文。這是可行的嗎?謝謝。

回答

3

上下文引用

是的,可以使用jinja2.nodes.ContextReference()。請參閱API參考here

放鬆,我要引導你度過它。 :)

首先擴展:

class ActiveCheckerExtension(jinja2.ext.Extension): 
    """ 
    This will give us a {% check_active %} tag. 
    """ 

    template = 'Active is : %s' 
    tags = set(['check_active']) 

    def _render_tag(self, context, caller): 
     return jinja2.Markup(self.template % unicode(context['active'])) 

    def parse(self, parser): 
     ctx_ref = jinja2.nodes.ContextReference() 
     lineno = next(parser.stream).lineno 
     node = self.call_method('_render_tag', [ctx_ref], lineno=lineno) 
     return jinja2.nodes.CallBlock(node, [], [], [], lineno=lineno) 

然後讓我們把它添加到瓶的Jinja2的。

app.jinja_env.add_extension(ActiveCheckerExtension) 

現在在你的模板,你可以這樣做:

{% check_active %} 

確保active在所有模板中定義你的標籤添加到,否則你會得到一個KeyError因爲上下文贏得沒有那個模板變量。