简体   繁体   English

如何使用对 Django 模板的静态文件引用注入 HTML 代码

[英]How to inject HTML code with static file reference to Django template

I have a simple use case in which I need to dynamically add rows to a table in my HTML template.我有一个简单的用例,我需要将行动态添加到 HTML 模板中的表中。 I am using the following javascript code to add this on a button click:我正在使用以下 javascript 代码在单击按钮时添加它:

function add_row(){
   row_html = '<tr><td><img src="path/to/my/file.png"></td></tr>'
   $('#table-id').append(row_html);
}

The only problem is that the image is not being found.唯一的问题是找不到图像。 I have also tried using Django template language, doesn't work.我也尝试过使用 Django 模板语言,不起作用。 One solution is defining the src in the script tag in my HTML template like in this question .一种解决方案是在我的 HTML 模板中的脚本标记中定义 src,就像在这个问题中一样 However I am not sure this is the optimal approach.但是我不确定这是最佳方法。

What is the correct approach to solve this problem?解决这个问题的正确方法是什么?

I don't know that this will work or not but try like this first create a variable which will get current URL like this我不知道这是否可行,但尝试像这样首先创建一个变量,它将像这样获取当前的 URL

before first try like this it this don't work than try another example在第一次尝试这样之前,这比尝试另一个例子不起作用

let staticUrl = "{% static 'my/path/to/image/inside/static/folder' %}"

function add_row(){
       row_html = `<tr><td><img src=${staticUrl}></td></tr>`
       $('#table-id').append(row_html);
    }

let protocol = window.location.protocol //get protocol eg. http:
let hostname = window.location.hostname // get hostname eg. stackoverflow.com
let port = window.location.port // get port eg. 8000

Note : In production you don't need port so before deploying it make sure to remove it注意:在生产中您不需要端口,因此在部署之前确保将其删除

let myUrl = protocol+hostname+port // this will return full URL
let staticUrl = "{% static 'my/path/to/image/inside/static/folder' %}"

function add_row(){
   row_html = `<tr><td><img src=${staticUrl}></td></tr>`
   $('#table-id').append(row_html);
}

let me know if this works.让我知道这个是否奏效。 (: (:

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

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