1

I'm trying to build a simple flask page that displays links from a dictionary of text/links:

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)

My template page looks like this:

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

I can't quite seem to understand how to create dynamic urls like this. The code produces this error:

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

Can anyone point out my problem or a solution?

UPDATE: Here's my updated code:

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

And the template:

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

This solution is close, however each link get prepended with my app's url. In other words I get this:

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

I just want:

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

1 回答 1

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 构建 URL。就像你的情况一样:

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

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

于 2013-07-17T02:00:02.123 回答