In tornado, how can I use static_url() in a class without tornado.web.RequestHandler?

3.9k views Asked by At

I'm using Tornado and I want to load some static files in the template. Now I use tornado.web.UIModule to load them. But I got some errors which said static_url() is not defined. So I looked up the documentation and found this function is a method of tornado.web.RequestHandler. But how can I load the static files like this function in my class below?

# _ * _ coding:utf-8 _ * _

import tornado.web
from tornado import template

class Header(tornado.web.UIModule):
"""docstring for Header"""
def render(self, hightlight = "index"):
    return self.render_string("header.html", hightlight = hightlight)

def css_files(self):
    css = [
        static_url("css/smoothness/jquery-ui-1.8.20.custom.css"),
        static_url("css/common.css"),
        static_url("css/jquery.jqplot.min.css"),
        static_url("css/blue/style.css"),
        static_url("css/jquery.vector-map.css")
    ]
    return css;

def javascript_files(self):
    javascript = [
        static_url("js/convert.color.js"),
        static_url("js/jquery-1.7.2.min.js"),
        static_url("js/jquery-ui-1.8.20.custom.min.js"),
        static_url("js/common.js"),
        static_url("js/jquery.jqplot.min.js"),
        static_url("js/plugins/jqplot.highlighter.min.js"),
        static_url("js/plugins/jqplot.cursor.min.js"),
        static_url("js/plugins/jqplot.dateAxisRenderer.min.js"),
        static_url("js/plugins/jqplot.canvasTextRenderer.min.js"),
        static_url("js/plugins/jqplot.canvasAxisLabelRenderer.min.js"),
        static_url("js/jquery.vector-map.js"),
        static_url("js/china-cn.js"),
        static_url("js/jquery.tablesorter.min.js"),
        static_url("js/charts.js")
    ]
    return javascript

def html_body(self):
    return "<!--[if lt IE 9]><script src=\"{{ static_url(\"js/excanvas.js\") }}\"></script><![endif]-->"

def embedded_javascript(self):
    return "<script>var current = null;</script>"
2

There are 2 answers

4
Cole Maclean On BEST ANSWER

You don't need to. If you give a relative path (in javascript_files and css_files, Tornado will automatically run it through static_url.

2
vartec On

As you already mentioned, static_url is a method of tornado.web.RequestHandler, but you're calling it as a global function.

Change

static_url(...)

to

self.handler.static_url(...)