Search code examples
javascriptpythonbottle

Can I use javascript with bottle (framework)?


I'm trying to display a page of html using bottle (the python web framework). The page has javascript embedded but it won't display it when I serve it with bottle.

The JS I'm using is EditArea, I can clean it up how I want and put it an html page that displays properly when I open the page in chrome. But when I use bottle:

@route('/edit')
def edit():
    return template('editarea')


@route('/edit_area')
def edit_area():
    send_file('example1.html', root='path/to/file/')

and go to http://localhost:8080/edit or /edit_area, I see the page without any of the fancy javascript features.

Eventually I want to hook this up (EditArea is text area and I'll be using it to accept code which hopefully I'll be able to run... but that's a separate issue...), but right now all it's supposed to do is display the page and the javascript. The JS is put in the html as simply as possible. Those two blocks use different files but they are just copies of the same html file, one with .html and the other with .tpl extensions.

<title>EditArea - the code editor in a textarea</title> 
    <script language="Javascript" type="text/javascript"     src="../edit_area/edit_area_full.js"></script> 
    <script language="Javascript" type="text/javascript"> 
        // initialisation
        editAreaLoader.init({

...and then it's all of the JS code (that I didn't write).

In the file to start the server I import: route, run, debug, template, request, send_file, and error from bottle; and sqlite3; but that's all. Is there something else I should be including?

I've looked into the bottle documentation, and a few other places and it's either something really obvious that nobody bothers to write down or it's something that people just don't do...

I was looking at pyjamas (it keeps coming up with different combinations of search queries involving "python" and "javascript"), but it looks like that just converts python into javascript. I don't think that's what I want b/c the javascript is already javascript...

Thanks for any insight you might have.


Solution

  • If you're using the template system included in Bottle called SimpleTemplate then it does not support multi line strings and the templates get compiled to executable Python bytecode. So its likely any Javascript would be stripped out.

    The only way to include javascript in your page would be via script tags as you did for the "edit_area_full.js" file.