2017-08-16 53 views
2

。在如下圖所示添加破折號我想在我的網址添加幾許瓶時自動生成的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),該網址會是這樣xxx.title title,我應該怎麼做才能在網址中添加短劃線,如xxx.title_title

而且我不希望在我的標題加破折號(例如,標題爲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 %} 
+0

你想創建一個'POST'紀錄標題**「這是標題」 ** **或「this_is_a_title」 **?你如何發送帖子請求?提交表單?使用HTTP客戶端請求,郵遞員?一般來說,當URL包含空格時,空格在html charset中被替換爲%20;即Chrome會自動替換空格。通常情況下,你不需要擔心它。 – ohannes

+0

我通過提交表單發送發佈請求,我不想更改我的標題,所以我想出了這個問題。正如你所說,但Firefox沒有將'空間'改爲'%20' – simp1e

回答

0

很高興看到您的模板。

無論如何,這裏是你的問題的一個可行的解決方案。

重要的是你如何構造的細節網址模板。

url_for使用一個參數。另外,當您顯示帖子的詳細信息頁面(包括其標題中的空格)時,請檢查瀏覽器地址欄。

所有的html charset替換將由模板引擎執行,所以你不必擔心它。

在您的實現,您可以根據您可能正在使用SQLAlchemy的ORM刪除get_post方法和POSTS列表。他們只是爲了快速測試。

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) 

模板/ 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> 

模板/ post_detail.html

<html> 
    <body> 
    <h1>POST DETAIL</h1> 
    <h3>{{ post.title }}</h3> 
    </body> 
</html> 

合e,它有幫助。

+0

感謝您的幫助。但我認爲你不明白或者讓你困惑。我想要的是在URL中將'space'變成'_',而不在參數'title'中輸入,我不想在標題中添加短劃線。 – simp1e

+0

是的,我真的很困惑。誰在您的網址中添加破折號?爲什麼你需要用下劃線替換空格?而且,如何通過標題用下劃線過濾記錄,而其原始形式是否包含數據庫中的空格?如果您可以展示您的相關模板,我會盡力理解並幫助您。 – ohannes

+0

因爲我覺得很難用空格填充地址,所以我嘗試用下劃線替換空格。根據你的建議,我想出了一個想法,即將模板中的下劃線替換爲空格,(Jinja)模板爲'

{{post.title |替換('_','')}}

'。但我必須在標題中加下劃線。這只是一種折衷方法。但是,無論如何,非常感謝:) – simp1e