Python webapp to set all query vars to a js object

87 views Asked by At

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>

1

There are 1 answers

2
pbuck On

You're close:

  1. Move your call to test = web.input() to within your GET() 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.)
  2. Within index.html, use

    $var path = path
    

    The 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 '$'.

  3. Within your template layout.html, change your javascript to something similar to:

    var test = "$:page.path";
    var digitalData = {
        'page': {
            'path': $:page.path
         }
    };
    

    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 set page.path to an object, rather than just a string.