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

Categories

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...