2013-09-30 30 views
1

我想解決這個web2py問題,我想我對發生了什麼有一些基本的誤解。在web2py中的HTML模板解析

假設我有一家商店,並且我想在我的index.html有許多包裝盒的產品。我希望每個這樣的盒子都可以從模板中解析出來。

我試圖做的有以下架構。在控制器我有

def index(): 
    products = db().select(db.products.ALL) 
    return dict(products=products) 
index.html

{{for i in range(0,len(products)):}} 
    {{ context=dict(product=products[i]) }} 
    {{ =response.render('template.html', context)}} 
{{pass}} 

template.html我有類似

<div id=...> <h1> {{=product.price}} </h1>... 

的問題是,結果被讀取literaly。也就是說,瀏覽時index.html我看到html標籤:

enter image description here

我懷疑我的整個做法是錯誤的。應該怎麼做?

回答

3
{{for product in products:}} 
    {{=XML(response.render('template.html', product.as_dict()))}} 
{{pass}} 

在template.html:

<div id=...> <h1> {{=price}} </h1>... 

response.render()返回一個字符串,所有字符串都在模板中逃脫。爲防止逃跑,您必須將字符串包裝在XML()中。

上面還包括一​​些簡化。在for循環中,您可以直接遍歷products中的行,然後可以將單個產品行轉換爲字典並將該字典作爲上下文傳遞給template.html(因此,您可以參考price而不是product.price )。

請注意,如果您不需要在其他地方使用template.html,則可以直接將其內容直接移到index.html中的for循環中。