0

I have been trying to make a page which combines web.py and JavaScript, and with the following code:

$code: 
     def getContents(fname): 
          a = req.get(fname) 
          return a.content 

<script type="text/javascript"> 
     document.write("$getContents('http://mysite.net')"); 
</script> 

Here, req is passed on my template's $def with() function, being a module object of the Python Requests module, from which I execute methods.)

Problem is, the document is blank, which means the document.write function got no input. Is there a way around this? Am I doing this in a wrong way?

EDIT: The function output is not empty; if you use plain HTML to print it it will just work.

Thanks in advance.

(I've also posted this question on the web.py Google group, got no answer yet.)

1
  • Can you show the "View Source" contents of the rendered page? Commented Nov 24, 2011 at 8:08

2 Answers 2

1

You can enable json encoder in template globals, and use it in your javascript code.

import json
template_globals = {"json_encode": json.dumps}
render = web.template.render(config.template_dir, globals=template_globals, base="layout")

Then in your template

<script>
var obj = $:json_encode({"html": getContents('http://mysite.net')});
document.write(obj.html);
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps you have quotes in rendered content, and it invalidates javascript.

5 Comments

Why won't you show the source of generated page? It will be easy to see the problem.
The source is at pastie.org/2914370; it renders matoe.co.cc/patcher.txt for an test.
The problem is that your javascript string is broken by the line breaks.
So is there a way to escape \n instead of NEWLINE? (You're right :))
Check my second answer, just use json.dumps to properly encode string for javascript. You then won't have to worry about quotes or newlines, etc.

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.