How to load static files from view HTML in web2py?

MikeWyatt picture MikeWyatt · May 21, 2010 · Viewed 7.1k times · Source

Given a view with layout, how can I load static files (CSS and JS, essentially) into the <head> from the view file?

layout.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{{=T.accepted_language or 'en'}}">
    <head>
        <title>{{=response.title or request.application}}</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <!-- include requires CSS files
        {{response.files.append(URL(request.application,'static','base.css'))}}
        {{response.files.append(URL(request.application,'static','ez-plug-min.css'))}}
        -->
        {{include 'web2py_ajax.html'}}
    </head>
    <body>
        {{include}}
    </body>
</html>

myview.html

{{extend 'layout.html'}}
{{response.files.append(URL(r=request,c='static',f='myview.css'))}}

<h1>Some header</h1>
<div>
    some content
</div>

In the above example, the "myview.css" file is either ignored by web2py or stripped out by the browser.

So what is the best way to load page-specific files like this CSS file? I'd rather not stuff all my static files into my layout.

Answer

mdipierro picture mdipierro · May 21, 2010

In myview.html reverse the first two lines

{{response.files.append(URL(r=request,c='static',f='myview.css'))}}
{{extend 'layout.html'}}

Mind that 1.78.1 and 1.78.2 had a bug did not allow this to work. It was fixed in 1.78.3 on the same day. The response.file.append(...) can also be moved in the controller action that needs it. You are not supposed to put logic before extend but you define variables to be passed to the extended view.