Home > database >  Django: Include a template containing a script tag into another script tag
Django: Include a template containing a script tag into another script tag

Time:05-21

I want include a html file containing a script tag like this:
<script>$('#page-content').html('{% include "title.html" %}');</script>

title.html:
<script>document.title = "Hello World!"</script><p>Hello World!</p>

result:
<script>$('#page-content').html('<script>document.title = "Hello World!"</script><p>Hello World!</p>');</script>

Sadly, the browser won't execute it correctly due to the mulitple sets of script tags and I'm not quite sure how to solve it best

CodePudding user response:

Well, just $.html will not execute scripts appended, but plain javascript can.

// const content = `{% include 'title.html' %}`;
const content = `<script>alert("foo")</script>`;
const target = document.getElementById('page-content');

const range = document.createRange();
range.selectNode(target);
const fragment = range.createContextualFragment(content);
target.appendChild(fragment);  // Here script is executed, "foo" pops up
  • Related