Using Static files

28 views
Skip to first unread message

yingi keme

unread,
Jul 18, 2017, 9:53:11 AM7/18/17
to Django users
I have a javascript file in my app static directory.

However inside my javascript file. I want to make use of an image. That is:

Javascript file is d6.js and it contains this code

var imageBank = baseUrl + "static/Game/blank.gif";

And then my html has this

{% load staticfiles %}
<script src="{% static 'Game/d6.js' %}"></script>


However when i render my html file the javascript file is unable to locate the img file (blank.gif). How do i get to reference an img file inside the static directory?


Antonis Christofides

unread,
Jul 18, 2017, 10:27:53 AM7/18/17
to django...@googlegroups.com
Hi,

Define staticUrl in the base template, like this:

<script type="text/javascript">
staticUrl = "{% static '' %}";
</script>
<script type="text/javascript" src="{% static 'Game/d6.js' %}"></script>

Then, inside d6.js:

var imageBank = staticUrl + 'Game/blank.gif';

(It is also good practice to use a single JavaScript global variable, like
app.staticUrl, in order to not pollute the global namespace, but that's another
issue.)

Regards,

Antonis

Antonis Christofides
http://djangodeployment.com

yingi keme

unread,
Jul 18, 2017, 3:10:29 PM7/18/17
to django...@googlegroups.com
Okk

The static url you defined in the script. Isnt it supposed to be:

var staticUrl = "{% static %}";

I am thinking there is an error with the quotation mark u used. Am i correct?



Yingi Kem
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ea3a37fe-9d28-ac5d-93a5-5d54d40011ba%40djangodeployment.com.
> For more options, visit https://groups.google.com/d/optout.

yingi keme

unread,
Jul 18, 2017, 3:38:25 PM7/18/17
to django...@googlegroups.com
When i opened the console in my browser. It shows the error 'staticUrl is not defined'.

The problem i am having is this. You are making use of a static file (blank.gif) inside another static file (d6.js)

Do you have to load static files inside the d6.js much thesame way you load static files in your template?



Yingi Kem

> On 18 Jul 2017, at 3:25 PM, Antonis Christofides <ant...@djangodeployment.com> wrote:
>

yingi keme

unread,
Jul 18, 2017, 3:56:17 PM7/18/17
to django...@googlegroups.com
Antonis, i think i understand the logic now. Thanks for the help.

Yingi Kem

> On 18 Jul 2017, at 3:25 PM, Antonis Christofides <ant...@djangodeployment.com> wrote:
>
Reply all
Reply to author
Forward
0 new messages