How to include static files in template?


#1

I’m trying to include some javascript in my template,

<script type="text/javascript" src="/static/js/app.js"></script>

settings = {
    'DATABASE': {
        'URL': 'sqlite:///db.sqlite3',
        'METADATA': Base.metadata
    },
    'STATICS': {
        'ROOT_DIR': 'front/static',
        'PACKAGE_DIRS': ['apistar']
    },
    'TEMPLATES': {
        'ROOT_DIR': 'front/templates',
        'PACKAGE_DIRS': ['apistar']
    }
}

and I have this route:

Route('/static/{path}', 'GET', serve_static)

But I’m getting a 404 error on the app.js file. Is there something I’m doing wrong? The template renders.


#2

Oops! My script was called “main.js” not “app.js”.

Silly me.


#3

Hi, i’ve the same problem, and fix with that

app.py

from apistar import Include, Route, render_template
from apistar.handlers import static_urls

routes = [

Include(’/statics’, static_urls),

]

settings = {
    'STATICS': {
        'ROOT_DIR': 'statics',
        'PACKAGE_DIRS': ['apistar']
    },
    'TEMPLATES': {
        'ROOT_DIR': 'templates',
        'PACKAGE_DIRS': ['apistar']
    }
}

index.html

<script src="{{ static_url('index.js') }}"></script>
<link href="{{ static_url('index.css') }}" rel="stylesheet">

it must to exist but you can change the name, just is an example.

statics/index.js
statics/index.css
templates/index.html
app.py

Good Luck :wink: