【问题标题】:Generate dynamic URLs with Flask使用 Flask 生成动态 URL
【发布时间】: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。

标签: python flask


【解决方案1】:

试试这个:

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 将端点名称作为第一个参数,默认情况下是视图函数的名称。因此,您的视图函数 index() 的端点名称就是 'index'

【讨论】:

  • 这正是我想要的。谢谢你的解释。
猜你喜欢
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多