Django - serving a SPA from static folder

戏子无情 提交于 2019-12-04 11:42:11
giaco

I made it like this for Angular2 app with Django(it works without problems) - I think it can help you.

urls.py:

# catch-all pattern for compatibility with the Angular routes
url(r'^$', views.index),
url(r'^(?P<path>.*)/$', views.index),

views.py

def index(request, path=''):
    """
    Renders the Angular2 SPA
    """
    return render(request, 'index.html')

index.html

{% load staticfiles %}
...some other stuff...
<app-root>Loading... </app-root>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static  'js/materialize.min.js'%}"></script>

<!-- Angular app -->
<script type="text/javascript" src="{% static 'js/app/inline.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/vendor.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/main.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/scripts.bundle.js' %}"></script>¸

settings.py

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

My index.html is stored in templates directory, my js app files are stored in static/js/app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!