简体   繁体   English

将变量从javascript传递到Django模板

[英]Pass variable from javascript to django template

I want to send a string value as a javascript variable from client side to be used in the django-template. 我想从客户端发送字符串值作为javascript变量,以在django模板中使用。 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. 具体来说,字符串是图像的相对路径,将在django模板标签为static的django模板中使用。 The static files are on Amazon S3 and should be served using the static tag of django template. 静态文件位于Amazon S3上,应使用django模板的静态标签进行投放。

In django template, I need the variable photo_url from javascript. 在Django模板中,我需要javascript中的变量photo_url。

<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): 现在,在javascript中,我已经嵌入了一个跨度的内部HTML,其中有photo_url作为photo(/static/images/abc.png)的相对URL:

<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. 但是通过这种方式,即使我在javascript的innerhtml中包含了静态标记,也无法从S3提供静态文件。 What is the best way to do that(pass javascript variable to django template)? 做到这一点的最佳方法是什么(将javascript变量传递给Django模板)?

{% static %} is just a convenience tag, you can hardcode your static url anytime. {% static %}只是一个方便标记,您可以随时对您的静态URL进行硬编码。
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. 您将无法在{% static %}标记中使用js变量(无论是附加变量还是以任何方式),因为js随html一起呈现而未经任何处理。

If STATIC_URL is available in your template you can set global JS variable to store it like: 如果模板中有STATIC_URL则可以设置全局JS变量以将其存储为:

<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. 或者,您可以在模型上定义get_absolute_url()方法,以提供带有域的完整url。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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