【问题标题】:Displaying Python values in HTML在 HTML 中显示 Python 值
【发布时间】:2013-03-15 14:28:45
【问题描述】:

如何在 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>
'''

【问题讨论】:

标签: python html google-app-engine


【解决方案1】:
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>

【讨论】:

  • +1 感谢您的回复和建议。我将学习和使用 jinja2。但由于我是 Python 和 GAE 的新手,我认为将 html 粘贴到 python 脚本中可能更简单。
【解决方案2】:

我对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)

【讨论】:

  • 不错的选项 - 另请参阅下面的一个,它显示了如何显式转义 HTML 值以防止跨站点脚本攻击。
【解决方案3】:

您的直接输出可能是:

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

先看一个基本的django模板

getting started with templates

那可能看看jinja2

jinja2 templates

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2021-07-27
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    相关资源
    最近更新 更多