RXR*_*XRO 5 python postgresql url-routing jinja2 flask
我正在学习 Flask,但我被困在这里了。
如何为带有参数(参数)的搜索结果建立链接?
我的应用程序搜索书籍并仅使用 Flask 和 Jinja2 以及 HTML 将它们呈现在 HTML 页面上。
所以我的HTML只有这个功能:
<ul>
{% for x in lk1 %}
<li><a href="{{ url_for('bookPage'}}">{{ x[2] }} (by) {{ x[3] }} (year) : {{ x[4] }}</a></li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
其中
lk1
是 Flask 从 SQL 收集的书籍列表,x
是来自 SQL 数据库的原始信息
现在在页面中bookpage.html
它是空的,我需要传递带有 URL 的参数,以便我可以将它们呈现在页面上或获取有关本书的其余信息并将其呈现在书页中,如果您可以帮助我了解如何制作该书的 URL书名是根据我的代码,{{ x[2] }}
我看到 ppl 做了类似的事情<url_titl>
,但我不知道它是如何工作的
谢谢你!
我认为,您必须学习有关使用 Flask 和 jinja 创建变量 url 的信息。
变量 url 的示例。
超文本标记语言
<ul>
{% for x in lk1 %}
<li><a href="{{ url_for('bookPage', title=x[2] }}">{{ x[2] }} (by) {{ x[3] }} (year) : {{ x[4] }}</a></li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
Python
@app.route('/books/<title>' )
# the name of this function have to be used in
# url_for ('nameOfFunction', name_of_variable_part_of_url=some_internal_variable)
def bookPage(title):
# code, that will creat yourlist
# book.html - template for book
# listofvariables - variables for book's page
#
return render_template ("book.html", listofvariables=yourlist)
Run Code Online (Sandbox Code Playgroud)
链接到类似的问题:Reference template variable inside Jinja expression
更新:要在 url 中使用许多变量,您必须更改 html 和 python。
网页:
<a href="{{ url_for('bookPage', title=x[2], heading=x[3]) }}">all your text </a>
Run Code Online (Sandbox Code Playgroud)
Python:
@app.route('/books/<title>-<heading>' )
def bookPage(title, heading):
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31119 次 |
最近记录: |