简体   繁体   中英

Django: How to load javascript from static files with template usage

I have a problem:

in addWorkout.html:

{% extends "workout/base.html" %}
{% block footer %}
<script type="text/javascript" src="{% static js/addWorkout.js %}"></script>
{% endblock %}

in base.html:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<body>

{% block content %}{% endblock %}

{% block footer %}{% endblock %}

</body>
</html>

This will generate an error:

Invalid block tag on line 49: 'static', expected 'endblock'. Did you forget to register or load this tag?

This error stems from the src attribute of the script tag in addWorkout.html . Apparently, django doesn't allow for the static tag to be inside of a block tag.

But how can I then import javascript from static by using the script -tag at the bottom of the body element?

EDIT:

If I change addWorkout.html to:

{% extends "workout/base.html" %}
{% load static %}
{% block footer %}
<script type="text/javascript" src="{% static js/addWorkout.js %}"></script>
{% endblock %}

I'll get the following error:

在此处输入图片说明

Child templates don't inherit the tags libraries loaded by their parents, you have to explicitely load static tags in your addWorkout template. Note that this is documented ...

I was able to reproduce the same error after removing the static tag from the extended template file, change the code as below and give it a try

{% extends "workout/base.html" %}
{% load static %}
{% block footer %}
<script type="text/javascript" src="{% static js/addWorkout.js %}">
</script>
{% endblock %}

Replace your addWorkout.html with the above code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM