当flask自动生成URL时,我想在URL中添加破折号。
代码如下所示:
@main.route('/post_detail/<string:title>', methods=['GET', 'POST'])
def post_detail(title):
post = Post.query.filter_by(title=title).first_or_404()
return render_template('post_detail.html', post=post)
由于我在路由中使用FLASK内置的转换,因此当title中有空格(例如title is
title title
)时,URL将像这样的xxx.title title
,我应该怎么做才能在URL中添加破折号,例如< cc>。而且我不想在标题中添加破折号(例如,标题为
xxx.title_title
)这是我的模板:
post_detail.html
<h1 color='black'>{{ post.title | replace('_', ' ') }}</h1>
<h2 class="subheading">{{ post.summary }}</h2>
<span class="meta">Posted by <a href="#">{{ post.author.username }}</a></span>
`和post_list.html
{% for post in posts %}
<div class="post-preview">
<a href="{{ url_for('main.post_detail', title=post.title) }}">
<h2 class="post-title">{{ post.title }}</h2>
<h3 class="post-subtitle">{{ post.summary }}</h3>
</a>
<p class="post-meta">Posted by <a href="#">{{ post.author.username }}</a></p>
</div>
{% endfor %}
最佳答案
最好看看您的模板。
无论如何,这是您的问题的可行解决方案。
重要的是如何在模板中构造详细信息URL。
请参见url_for
与参数的用法。另外,在显示帖子的详细信息页面(包括标题中的空格)时,请检查浏览器的地址行。
html字符集的所有替换将由模板引擎执行,因此您无需担心。
在您的实现中,可以删除get_post
方法和POSTS
列表,因为您可能正在使用SQLAlchemy ORM。它们只是为了快速测试。
app.py
from flask import Flask, abort, render_template
main = Flask(__name__)
POSTS = [
{'title': 'this_is_a_title'},
{'title': 'this_is_another_title'},
{'title': 'this title contains space'},
]
def get_post(title):
for post in POSTS:
if post['title'] == title:
return post
return None
@main.route('/post_list', methods=['GET', 'POST'])
def post_list():
return render_template('post_list.html', posts=POSTS)
@main.route('/post_detail/<string:title>', methods=['GET', 'POST'])
def post_detail(title):
#post = Post.query.filter_by(title=title).first_or_404()
post = get_post(title)
if post is None:
abort(404)
return render_template('post_detail.html', post=post)
if __name__ == '__main__':
main.run(debug=True)
templates / post_list.html
<html>
<body>
<h1>POST LIST</h1>
{% for post in posts %}
<h3>{{ post.title }}</h3>
<a href="{{ url_for('post_detail', title=post.title) }}">details</a>
{% endfor %}
</body>
</html>
templates / post_detail.html
<html>
<body>
<h1>POST DETAIL</h1>
<h3>{{ post.title }}</h3>
</body>
</html>
希望能帮助到你。
关于python - 在网址中添加破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718039/