1
我試圖建立一個從文本/鏈接的字典顯示指向一個簡單的燒瓶頁:生成動態的URL與瓶
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__'
任何人都可以指出我的問題或解決方案?
UPDATE:這是我更新的代碼:
@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 %}
該解決方案是接近的,但是每一個環節得到我的應用程序的網址前綴。換句話說,我得到這個:
<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>
你知道'url_for'的用途嗎?它將所謂的端點作爲第一個參數。你只是想要一個鏈接列表?另外,究竟是什麼「urls」? – dAnjou
是的,確切地說。我只想從url的字典中構建一系列鏈接,其中關鍵是文本,值是url。 – turtle