使用Flask生成动态URL

时间:2013-07-17 00:24:19

标签: python flask

我正在尝试构建一个简单的烧瓶页面,显示文本/链接字典中的链接:

urls = {'look at this page': www.example.com, 'another_page': www.example2.com}   

@app.route('/my_page')
def index(urls=urls):
    return render_template('my_page.html',urls=urls)

我的模板页面如下所示:

{%- block content %}
{%- for url in urls %}
    <a href="{{ url_for(urls.get(url)) }}">{{ url }}</a>
{%- endfor %}
{%- endblock content %}

我似乎无法理解如何创建这样的动态网址。代码产生此错误:

TypeError: 'NoneType' object has no attribute '__getitem__'

有人可以指出我的问题或解决方案吗?

更新:这是我更新的代码:

  @app.route('/my_page')
    def index():
        context = {'urls': urls}
        return render_template('index.html', context=context)

模板:

{%- block content %}
    {% for key, data in context.items() %}
        {% for text, url in data.items() %}
            <a href="{{ url }}">{{ text }}</a>
        {% endfor %}
    {% endfor %}
{%- endblock content %}

此解决方案已关闭,但每个链接都会以我的应用程序的URL为前缀。换句话说,我明白了:

<a href="http://127.0.0.1:8000/www.example.com">look at this page</a>

我只想:

<a href="http://www.example.com">look at this page</a>

1 个答案:

答案 0 :(得分:3)

请改为尝试:

urls = {
    'A search engine.': 'http://google.com',
    'Great support site': 'http://stackoverflow.com'
}

@app.route('/my_page')
def index(): # why was there urls=urls here before?
    return render_template('my_page.html',urls=urls)

{%- block content %}
{%- for text, url in urls.iteritems() %}
    <a href="{{ url }}">{{ text }}</a>
{%- endfor %}
{%- endblock content %}

url_for仅用于使用Flask构建网址。就像你的情况一样:

print url_for('index') # will print '/my_page' ... just a string, no magic here

url_for将端点名称作为第一个参数,默认情况下是视图函数的名称。因此,视图函数index()的端点名称只是'index'

相关问题