1

テキスト/リンクの辞書からのリンクを表示する単純なフラスコページを構築しようとしています:

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 %}

このような動的 URL を作成する方法がよくわかりません。コードは次のエラーを生成します。

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>
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_forFlask で 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 に答える