3

How do I display the value of a python variable (in this case it is the key of my Entity class) in html?

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>
'''
1

3 Answers 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))

I would seriously advise you to use templates though it makes your life much easier.

With a template your solution would be something like this:

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}))

and the Mytemplate.html file would look like:

 <html>
   <head></head>
    <body>
     <label>{{key_val}}</label>
     <br>            
    </body>
 </html>
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Thanks for your reply and advice. I'll learn and use jinja2. But since I'm new to both Python and GAE, I thought it might be simpler for me to paste the html in the python script.
3

I don't know much about google app engine, but in Python, there are two ways:

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

Second:

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

Actually, there is the third way, which I prefer because it is explicit:

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

1 Comment

Nice optons - also see one below which shows how to escape HTML values explicitly to prevent cross-site scripting attacks.
1

Your immediate output could be:

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

First have a look at a basic django template

getting started with templates

Then possibly have a look at jinja2

jinja2 templates

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.