【发布时间】:2023-03-28 11:31:02
【问题描述】:
我正在尝试构建一个简单的烧瓶页面,该页面显示来自文本/链接字典的链接:
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>
【问题讨论】:
-
你知道
url_for是干什么用的吗?它采用所谓的端点作为第一个参数。你只想要一个链接列表吗?另外,urls到底是什么? -
是的,完全正确。我只想从 url 字典中构建一系列链接,其中键是文本,值是 url。