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