2013-07-17 41 views
1

我試圖建立一個從文本/鏈接的字典顯示指向一個簡單的燒瓶頁:生成動態的URL與瓶

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 %} 

我似乎無法理解如何創建像這樣的動態URL。該代碼產生此錯誤:

TypeError: 'NoneType' object has no attribute '__getitem__' 

任何人都可以指出我的問題或解決方案?

UPDATE:這是我更新的代碼:

@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> 
+0

你知道'url_for'的用途嗎?它將所謂的端點作爲第一個參數。你只是想要一個鏈接列表?另外,究竟是什麼「urls」? – dAnjou

+0

是的,確切地說。我只想從url的字典中構建一系列鏈接,其中關鍵是文本,值是url。 – turtle

回答

3

試試這個:

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只有建立網址瓶。像你的情況:

print url_for('index') # will print '/my_page' ... just a string, no magic here 

url_for接受端點名稱是默認視圖函數的名稱第一個參數。因此,您的視圖功能index()的端點名稱僅爲'index'

+0

這正是我所期待的。感謝您的解釋。 – turtle