Reputation: 3145
I want to send a string value as a javascript variable from client side to be used in the django-template. Specifically, the string is the relative path of an image and it is to be used in the django template with the django template tag static. The static files are on Amazon S3 and should be served using the static tag of django template.
In django template, I need the variable photo_url from javascript.
<img class = "main-img" src = "{% static photo_url %}" alt="main photo" />
For now, In javascript, I have embedded the innerhtml of a span with photo_url as relative url of photo(/static/images/abc.png):
<img class = "main-img" src = ' + photo_url + ' alt="main photo" />
But this way, I cannot serve static files from S3 even if I include the static tag in the innerhtml in javascript. What is the best way to do that(pass javascript variable to django template)?
Upvotes: 1
Views: 1444
Reputation: 6162
If STATIC_URL
is available in your template you can set global JS variable to store it like:
<script>
STATIC_URL = '{{ STATIC_URL }}';
</script>
Then wrap creation of photo url in function
function photo_url(photo) {
return STATIC_URL + photo_url;
}
This way you'll be able to achieve what you want.
Alternatively you can define get_absolute_url()
method on your models to provide full url with domain.
Upvotes: 0
Reputation: 5172
{% static %}
is just a convenience tag, you can hardcode your static url anytime.
You will not be able to use js variables (either appending them or anyhow) in {% static %}
tag because js gets rendered along with html without any processing.
Upvotes: 1