简体   繁体   English

将 JS 值插入 Django 模板

[英]Insert JS value to Django template

As I am exploring Web Development, I require small assistance here.由于我正在探索 Web 开发,我在这里需要一些帮助。 In my case, I have a folder with static images.就我而言,我有一个包含 static 图像的文件夹。 To display an image I need to get data from API, let's say, some pointer on which particular image should be displayed.要显示图像,我需要从 API 获取数据,比如说,应该显示哪个特定图像的一些指针。

<img class="some_img" src="{% static 'image_PIONTER.png' %}">

I'm getting that pointer using JS in a separate file script.js.我在单独的文件 script.js 中使用 JS 获取该指针。 To achieve what I want I need to replace POINTER in the src attribute of html with some actual word (lets say 'Captain') to get an image 'image_Captain.png' from static files.为了实现我想要的,我需要将 html 的 src 属性中的 POINTER 替换为一些实际单词(比如说“船长”),以从 static 文件中获取图像“image_Captain.png”。 How could I get this POINTER from a JS to django template?如何从 JS 到 django 模板中获取此指针? As I already know, Django renders its templates before any client side (JS code) executed.正如我已经知道的那样,Django 在执行任何客户端(JS 代码)之前呈现其模板。 So I cant just pass this attribute or even a part of html as $().html or $().append.所以我不能只将这个属性甚至 html 的一部分作为 $().html 或 $().append 传递。 It won't work.它行不通。 Picture should be displayed on a button click, preferably without refreshing the whole page.图片应该在按钮点击时显示,最好不要刷新整个页面。 Thanks in advance提前致谢

Try using Vue.js if you haven't.如果没有,请尝试使用 Vue.js。 You can pull it from a CDN with您可以使用以下命令从 CDN 中提取它

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>

<button @click = "someFunction()">Click me</button>
<div id = "vueApp">
<img v-if = "result" v-bind:src = "result">
</div>

Then just add a script tag like so and create a Vue instance(replace things inside two '+' with your values):然后像这样添加一个脚本标签并创建一个Vue实例(用你的值替换两个'+'内的东西):

<script>
var search = new Vue({
        el: '#vueApp',
        delimiters: ["[[", "]]"],
        data(){
            return{
                result: ""
            }
        },
        mounted(){
            console.log("This is mounted")
        },
        methods:
        {   
          someFunction: function()
          {
             axios.get(`+SomeAPI+`).then((response) => 
                        {
                        this.result = (response.data)
                        }).catch((function(error)
                        {
                        console.log(error);
                        }
                        ));
                        
          }
        }
    })
</script>

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

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