0

I am using AppEngine with the webapp framework (python). In my script I am generating javascript code dynamically with Django, for example:

python controller file

template_values = {
    'page': '1',               
}

path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))

index.html file

<html>
<head>
...
<script>
{% if page %}
   alert("test");
{% endif %}
</script>
</head>
<body>

...
</body>
</html>

Now, instead of using inline <script> tags I would like to use the <link> tags with a reference to a JS file containing the script. However, I can't quite understand I can do that using the templates engine. If I include a JS file (dynamically) it would somehow have to know the value of "page", but "page" is known in the scope of index.html only.

Any ideas?

Thanks,

Joel

Joel
  • 5,949
  • 12
  • 42
  • 58

2 Answers2

0

You are either over-complicating a simple situation, or you haven't explained your problem clearly.

If you want to include an externally-located JavaScript file, you would use a <script> tag, not <link>.

If you have template code like this:

<html>
<head>
{% if page %}
   <script type="text/javascript" src="/js/foo.js"></script>
{% endif %}
</head>
...
</html>

and page is not None, the template will render the following HTML to the browser:

<html>
<head>
   <script type="text/javascript" src="/js/foo.js"></script>
</head>
...
</html>

and the browser will try to load the resource pointed to by the <script> tag. The browser has no knowledge of how that tag got into the HTML that it loaded.

Adam Crossland
  • 14,198
  • 3
  • 44
  • 54
  • from the example code it's clear the user would like to place templating code inside a javascript file. – citronic Oct 25 '12 at 12:29
0

If you want dynamically generate your javascript code in your html, you can write the code inside python code

page = 0
template_values = {
    'js_code': 'alert("test:'+str(page)+'")',               
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))

in index.html

<script>
{{js_code}}
</script>

If you want to generate a js file dynamically, you can try to pretend there is a js file, and generate its content.

class JSHandler(BaseHandler):
    def get(self):
        page= str(self.request.get("page"))
        js_code ='alert("page:'+page+'");'
        self.response.out.write(js_code)


def main():
 application = webapp.WSGIApplication([
  ('/code.js', JSHandler),
    ], debug=True)
 wsgiref.handlers.CGIHandler().run(application)

Then you can write this code in your html

<script type="text/javascript" src="/code.js?page={{page}}">></script>
KTU
  • 445
  • 4
  • 16