3

如何在 html 中显示 python 变量的值(在这种情况下,它是我的 Entity 类的键)?

from google.appengine.ext import db

class Entity(db.Expando):
    pass

e = Entity()    
e.put()         # id is assigned
k = e.key()     # key is complete
id = k.id()     # system assigned id

html='''
<html>
    <head></head>
    <body>
        <label>Key: %(k) </label>
        <br>            
    </body>
</html>
'''
4

3 回答 3

5
from google.appengine.ext import db
import cgi

class Entity(db.Expando):
    pass

e = Entity()    
e.put()         # id is assigned
k = e.key()     # key is complete
id = k.id()     # system assigned id

html="""
<html>
    <head></head>
    <body>
        <label>Key: %s </label>
        <br>            
    </body>
</html>""" % (cgi.escape(k))

我会认真建议您使用模板,尽管它会让您的生活更轻松。

使用模板,您的解决方案将是这样的:

class Entity(db.Expando):
pass

e = Entity()    
e.put()         # id is assigned
k = e.key()     # key is complete
id = k.id()     # system assigned id

template = jinja_environment.get_template('templates/myTemplate')
self.response.write(template.render({'key_val':k}))

Mytemplate.html 文件看起来像:

 <html>
   <head></head>
    <body>
     <label>{{key_val}}</label>
     <br>            
    </body>
 </html>
于 2013-03-15T14:53:47.110 回答
3

我对google app engine了解不多,但是在Python中,有两种方式:

html='''
<html>
    <head></head>
    <body>
        <label>Key: %(k)s </label>
        <br>            
    </body>
</html>
''' % locals() # Substitude %(k)s for your variable k

第二:

html='''
<html>
    <head></head>
    <body>
        <label>Key: {0[k]} </label>
        <br>            
    </body>
</html>
'''.format(locals())

实际上,还有第三种方式,我更喜欢它,因为它是明确的:

html='''
<html>
    <head></head>
    <body>
        <label>Key: {0} </label>
        <br>            
    </body>
</html>
'''.format(k)
于 2013-03-15T14:46:11.743 回答
1

您的直接输出可能是:

<label>Key: {{k}} </label>

首先看一个基本的django模板

开始使用模板

然后可能看看jinja2

jinja2 模板

于 2013-03-15T15:03:39.867 回答