如何将参数传递给Flask Jinja模板函数?

时间:2015-10-28 04:53:54

标签: python flask jinja2

这样可行,但我喜欢将参数变量值传递给返回render_template()里面的部分,所以我可以重用test(),我该怎么做?

""" Test.html """
@app.route('/test')
def test():
    """Renders the careers page."""
    return render_template(
        'content/loader.html',
        title='Test',
        year=datetime.now().year,
        message='Your Test page.',
        main_nav_active_ = '',
        layout_template = '/layouts/default.html',
        content_template = 'clarity.html'
    )

我希望能够根据路线使用这样的功能

""" Test.html """
def test(title,year,message, main_nav_active_, layout_template, content_template)
    """Renders the careers page."""
    return render_template(
        'content/loader.html',
        title=title,
        year=year,
        message=message,
        main_nav_active_ = main_nav_active_,
        layout_template = layout_template,
        content_template = content_template
    )

@app.route('/test2')
test(title='test2',year=datetime.now().year,message='Your Test page.', main_nav_active_='', layout_template='/layouts/default.html', content_template='clarity.html')

@app.route('/test3')
test(title='test3',year=datetime.now().year,message='Your Test page3.', main_nav_active_='', layout_template='/layouts/default.html', content_template='foo.html')

2 个答案:

答案 0 :(得分:1)

只需提取test

def test(
        template='content/loader.html',
        title='Test',
        year=None,
        message='Your Test page.',
        main_nav_active_='',
        layout_template='/layouts/default.html',
        content_template='clarity.html'
    ):
    """Renders a particular page type."""
    return render_template(
        template,
        title=title,
        year=year if year is not None else datetime.now().year,
        message=message,
        main_nav_active_=main_nav_active_,
        layout_template=layout_template,
        content_template=content_template
    )

然后,您可以使用app.add_url_rule将其注册为URL,或将其用作其他路径定义的一部分:

app.add_url_rule("/test", "test", test)

# Or

@app.route("/another/<route>")
def alternatively(route_name):
    return test(title=route_name)

答案 1 :(得分:0)

def test(**kwargs)
    """Renders the careers page."""
    return render_template(
        'content/loader.html',
        **kwargs
    )

@app.route('/test2')
def test2():
    return test(title='test2',year=datetime.now().year,message='Your Test page.', main_nav_active_='', layout_template='/layouts/default.html', content_template='clarity.html')

@app.route('/test3')
def test3():
    return test(title='test3',year=datetime.now().year,message='Your Test page3.', main_nav_active_='', layout_template='/layouts/default.html', content_template='foo.html')