Home > Back-end >  use django "include" inside a js function
use django "include" inside a js function

Time:04-27

I am doing a search page in which parameters are sent by ajax and then upon reception of the queryset I rebuild my cards. The whole thing is classic and working ok, here is a simplified version of the thing. Lots of lines killed or modified since it is not really the subject of the post

let getobject = async (value,url) => {
    var res2 = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            "X-CSRFToken": getCookie("csrftoken"),
        },
        body: JSON.stringify({
            value: value,
        })
    })
    let data2 = await res2.json();
    videoitems.innerHTML = ''
    modalbin.innerHTML = ''
    data2["data"].forEach(async item => {
        if (item.ext == '.mp4') {
            const dynamicreation = async () => {
                let dyncontent3 = await createnewcard(item)
                let placing = await videoitems.appendChild(dyncontent3);
            }
            const nooncares2 = await dynamicreation()
        } else if (item.ext == ".pdf") {
            const dynamicreation2 = async () => {
                let dyncontent4 = await createnewcard(item)
                let placing2 = await videoitems.appendChild(dyncontent4);
            }
            const nooncares4 = dynamicreation2()
        }
    })
}

the createnewcard function

var createnewcard = item => {
    var dyncontent =  document.createElement("div");
      dyncontent.innerHTML = 
      `<div >
        <div data-reco="${item.id}"
          >
          <div >
            <p >
              ${item.title}
            </p>
          </div>
        </div>
      </div>`;
      return dyncontent
    }

What I would like to know is if it would be possible to mix this js with the django "include" function and instead of using js template litterals use an html component of the card that I would include upon looping in the data reveived. I could also maybe include it inside the createnewcard js function but so far it all failed quite miserably. Thanks a lot

CodePudding user response:

Yes, you've to create card.html or whatever you can name then you've to just include inside your js make sure you use same variables while looping in js eg.(item)

card.html

<div >
  <div data-reco="${item.id}"
          >
    <div >
       <p >
          ${item.title}
       </p>
    </div>
  </div>
</div>

and inside your Js do like this

var createnewcard = item => {
    var dyncontent =  document.createElement("div");
    dyncontent.innerHTML = {% include "card.html" %}
    return dyncontent
}

  • Related