我正在尝试构建一个简单的 flask 页面,显示文本/链接字典中的链接:
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 %}
这个解决方案很接近,但是每个链接都前面加上我的应用程序的网址。换句话说,我明白了:
<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>
最佳答案
试试这个:
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
将端点名称作为第一个参数,默认情况下是 View 函数的名称。因此, View 函数 index()
的端点名称就是 'index'
。
关于python - 使用 Flask 生成动态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689130/