简体   繁体   中英

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. I am using the following javascript code to add this on a button click:

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. One solution is defining the src in the script tag in my HTML template like in this question . 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

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. (:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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