谷歌App Engine模板文件中的字符串替换
我正在使用 Google App Engine(当然是 Python :)),我想对一个来自模板文件的字符串进行替换。
{% for item in items %} <p>{{ item.code.replace( '_', ' ' ) }}</p> {% endfor %}
但是这样并没有成功。所以我们在 App Engine 的模板中不能执行除了基本检查以外的其他操作。这是对的吗?
还有一个相关的问题是,我想缩短一个字符串,并让它在模板中可用。
每个家具对象都有一个名称和一个较长的描述字段。在我正在渲染的这个视图中,我只想显示描述字段的前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
但结果不太理想。
2 个回答
除了你代码里没有参数的 .fetch()
调用,我觉得这个肯定是行不通的(你总是得给 fetch
传个参数——也就是你想获取的最大实体数量!),我在测试中无法重现你遇到的问题——给每个项目分配一个新属性(包括通过处理现有属性得到的)在我这儿都能正常工作。
能不能请你尽量简化一下你遇到的问题,并更新你的提问,包含所有相关的文件?看起来这是我们能帮你解决这个奇怪问题的唯一办法!
顺便说一下,select name,LEFT( description, 50 )
或者其他类似的写法在 GQL 中当然是行不通的——GQL 非常明确地只支持 select *
来获取完整的实体,或者 select __key__
来只获取实体的键——就这些;在选择中不能选择列,更别提对它们进行任何操作了!
我对Google AppEngine了解不多,但我知道它和Django关系很紧密。你的模板里其实不包含Python代码,即使你用的一些结构看起来像是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 }}