Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.1k views
in Technique[技术] by (71.8m points)

How to insert a Django template tag + HTML element in a HTML page with Javascript

How can I safely add a piece of HTML with Django template tags in it using Javascript? For example, if I have something like this in my template:

<div id="some-element">
  <span id="my-tag">{{ my_data }}</span>
</div>
<!-- rest of the html page -->

If I were to use a script to just edit the innerHTML of the div, like the script below, it'd would just read {{ other-data }} as a string. How can I make it become an actual Django template tag?

<script>
  document.getElementById("some-element").innerHTML = 
    `
    <h1>This is may new data {{ other-data }} </h1>
    {% if value %}
      <p>This is an if statement</p>
    {% endif %}
    `
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Django template thing is not a client side thing, when a request comes to the server, Django renders the HTML file then responds with it, the HTML file gets manipulated on the Server

And you don't need Django to use conditionals, JS is already there to insert elements based on conditions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...