[英]Google appengine string replacement in template file
我正在使用google appengine(當然是python :)),我想對模板文件中的字符串執行string.replace。
{% for item in items %} <p>{{ item.code.replace( '_', ' ' ) }}</p> {% endfor %}
但這不起作用。 因此,除了應用程序引擎模板中的基本檢查之外,我們無法執行其他任何操作。 那是對的嗎 ?
另一個相關的問題是我正在嘗試縮短字符串並將其提供給模板。
每個家具對象都有一個名稱和一個較長的描述字段。 在此視圖中,我只需要描述字段的前50個字符。
所以我嘗試了類似的東西
items = db.GqlQuery( 'select * from furniture' ) # edit: if you change the above line to # items = db.GqlQuery( 'select * from furniture' ).fetch( 1000 ) # the .fetch() command makes the addition of dynamic properties work! for item in items : item.shortdescr = item.description[ 0:50 ] # pass data off to template for rendering self.response.out.write( template.render( 'furnitureAll.html', { 'items' : items } ) )
模板去
{% for item in items %} <p>{{ item.name }}</p> <p>{{ item.shortdescr }}</p> <!-- items.shortdescr does not exist here, probably because I did not .put() it previously. --> {% endfor %}
由於這不起作用,我嘗試更改Gql查詢來縮短字符串。 但是我很快意識到Gql不像SQL。 我正在嘗試編寫查詢
select name,LEFT( description, 50 ) from furniture
收效甚微
除了參數少.fetch()
在你的代碼調用,我相信不可能工作(你總是必須通過fetch
參數-實體的最大數量你願意取),我可以不能重現您的問題-在我的測試中,為每個項目分配一個新屬性(包括通過處理現有屬性獲得的屬性)就可以了。
您能否以盡可能小的指南針重現觀察到的問題,並編輯您的問題以包括所有相關文件? 似乎是我們唯一可以幫助您解決奇怪的bug的方法!
順便說一句, select name,LEFT( description, 50 )
或其他任何課程都不能在GQL中使用-GQL,非常明確地,僅支持select *
獲取整個實體,或select __key__
僅獲取實體的鍵-就這樣; 選擇中的列沒有選擇性,更不用說對其進行任何操作了!-)
我對Google AppEngine的經驗很少,但據我了解,它與Django有非常密切的關系。 您的模板實際上並不包含Python代碼,即使您在其中使用的某些結構看起來像它。
您的兩個問題都應使用模板過濾器解決。 如果是Django,我將使用類似以下內容的第二個問題:
{{ item.description|truncatewords:10 }}
對於第一個問題(字符串替換),可能沒有可用於此的內置過濾器。 您將需要自己編寫。 像這樣的東西;
from google.appengine.ext.webapp.template import create_template_register
register = create_template_register()
@register.filter
def replace_underscores(strng):
return strng.replace('_', ' ')
然后,您可以在模板中執行以下操作:
{{ item.code|replace_underscores }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.