Reputation: 4170
I have a template in django called base.html
that is calling another template through the {% include 'gui/page.html' %}
in that template I have the following javascript which allows the ability to select an an entire text field when setup like <p>This text I will select all</p>
<script>
$(document).ready(function(){
$('p').dblclick(function(e){
$(this).selectText();
e.preventDefault();
});
});
jQuery.fn.selectText = function(){
this.find('input').each(function() {
if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) {
$('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
}
$(this).prev().html($(this).val());
});
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
</script>
If I access the template directly @ http://localhost/gui/page.html
the javascript works, but if I access it through http://localhost/base.html
double clicking on the field does nothing.
I've tried including the javascript in the base.html and it still doesn't load. How does django load javascript when calling through an included template?
Upvotes: 5
Views: 10631
Reputation: 1
I came across same issue. I was not able to find any best solution with minimal change, so commenting here my perspective/solution to resolve this issue.
step1: Include alpine.js to your project.
step2: Include js function:
step3: In include template add x-init="your JS function" (from alpinejs) to the element. <div x-init="jsfunction"></div>
above is going to resolves the issue.
Upvotes: 0
Reputation: 5124
Just had the same issue. In order to solve it, it is necessary to do the next thing:
In base.html add:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
{% block extrascripts %}{% endblock %}
Put your hand-made script to /static/js/hand_made.js
In the child
template, which are included, i.e that one which we use in {% include 'child_template.html' %}
:
{% load staticfiles %}
{% block extrascripts %}<script type="text/JavaScript" src="{% static 'js/hand_made.js' %}"></script>{% endblock %}
(can not add it with a nice style for some reason).
If for some reasons you need to provide data from template to JS, you need to do the next:
{% block extrascripts %}
<script>
var my_var_1 = "{{ some_template_data.var_1 }}",
my_var_2 = "{{ some_template_data.var_12 }}";
</script>
<script type="text/JavaScript" src="{% static 'js/hand_made.js' %}"></script>
{% endblock %}
In this case my_var_1
and my_var_2
will be available in hand_made.js
Upvotes: 9
Reputation: 1731
Django does not modify or load any javascript in a template. It will simply pass it through to the output.
Upvotes: 1