I am building a simple web app with Python and web.py. My current challenge is to take all query vars (web.input()
) and set a JavaScript object in the HTML template. However, I don't know how to ensure this gets rendered OK instead of a long string with encoding.
Thanks a million!
I have the following code in app.py
, template HTML and content HTML:
app.py
:
import web
urls = (
'/hello', 'hello',
'/bye/', 'bye'
)
app = web.application(urls, globals(), autoreload=True)
#test = "testwaarde"
test = web.input()
render = web.template.render('templates/', base='layout')
class hello:
def GET(self):
return render.index("Templates demo",test, "Hello", "A long time ago...")
class bye:
def GET(self):
return render.hell_form("Templates demo",test, "Bye", "14", "8", "25", "42", "19")
if __name__ == "__main__":
app.run()
Template:
$def with (page)
<html>
<head>
<title>$page.title</title>
<!-- Digital Data Layer -->
<script>
var test = "{{$page.path}}"
var digitalData = {
'page':{
'path': '$page.path'
}
};
</script>
</head>
<body>
<p>You are visiting page <b>$page.name</b>.</p>
$:page
</body>
</html>
index HTML:
$def with (title, **path,name, content)
$var title:$title
$var name:$name
$var path:$path
<p>$content</p>
You're close:
test = web.input()
to within yourGET()
methods, not at the top of the file. That's just a bug. (I know that's just your sample code, but it doesn't work.)Within
index.html
, useThe using
var path: $path
sets the template variable to a string representation of path. You want to set it to the dict. That's one difference between the colon and the equal sign. Second, because it's '=', the right hand side is interpreted as python, so no leading '$'.Within your template
layout.html
, change your javascript to something similar to:You'll want to escape the data using
$:
rather than$
. That's why you're seeing the encoded values. Also, you don't want to surround the final$:page.path
with quotes to setpage.path
to an object, rather than just a string.