【问题标题】:Tornado - why does static files without StaticFileHandler donot work?Tornado - 为什么没有 StaticFileHandler 的静态文件不起作用?
【发布时间】:2015-08-05 11:12:18
【问题描述】:

我是 Tornado 的新手。我正在尝试将 CSS 文件链接到 html 模板。我正在将 jinja2 与 Tornado 一起使用。但由于某些未知原因,CSS 文件无法加载。

编辑:我创建了我的自定义 render_template 函数,该函数运行良好。

目录结构:

app.py
static
    css
        custom.css
templates
    index.html

这是我的请求处理程序的类:

class Index(RequestHandler):
def get(self):
    path = os.path.join('static/css/', 'custom.css')
    return self.write(render_template('index.html', path = path))

这是我的index.html 模板:

<!Doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="{{path}}"/>
  </head>
  <body>
    <div>
      <div class="header">
         asdasdasd
      </div>
    </div><!--wrapper-->
  </body>

</html>

但浏览器正在为具有正确 url 的 css 文件返回 404-NotFound 错误,即 @987654321@

【问题讨论】:

  • 你的目录结构是什么样的?
  • 我已经用结构编辑了问题

标签: python html css tornado


【解决方案1】:

这里是关于如何在 tornado 中链接静态文件的指南: http://tornado.readthedocs.org/en/latest/guide/running.html#static-files-and-aggressive-file-caching

重要的是设置字典中的“static_path”设置:

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static")
}

现在你应该可以使用它了。

【讨论】:

  • 谢谢,只有一件事,static_url 在 jinja2 中不起作用。你知道它的任何等价物吗?
  • 对不起,我对jinja2一无所知。
  • 你应该可以做 static_url 就好了。 path = self.static_url( css/'custom.css')
猜你喜欢
  • 2013-10-08
  • 2016-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
相关资源
最近更新 更多