最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Move all Javascript to a separate file in Django - Stack Overflow

programmeradmin3浏览0评论

I'm beginning with Django and doing some stuff. I want to keep html files clean, without <script> blocks. Is it possible, even if my js part is using {% url %} blocks?

Example:

page.html

<div> 
<h1> My home url is: </h1>
<div id="js-tag" ></div>
</div>
<script>
$(function(){
  $('#js-tag').html("{% url 'home' %}")
});
</script>

What I want to is remove this and place it on a separate js file and just import it to page.html

I'm beginning with Django and doing some stuff. I want to keep html files clean, without <script> blocks. Is it possible, even if my js part is using {% url %} blocks?

Example:

page.html

<div> 
<h1> My home url is: </h1>
<div id="js-tag" ></div>
</div>
<script>
$(function(){
  $('#js-tag').html("{% url 'home' %}")
});
</script>

What I want to is remove this and place it on a separate js file and just import it to page.html

Share Improve this question edited Apr 17, 2015 at 14:27 Kayan Almeida asked Apr 17, 2015 at 13:54 Kayan AlmeidaKayan Almeida 6118 silver badges15 bronze badges 2
  • What do you mean by "without <script> blocks"? You have to bind your JavaScript files to your HTML files. I don't know how this could be done without <script src="yourjavascript.js"> direction. – cezar Commented Apr 17, 2015 at 14:04
  • I edited my question, sorry @cezar. Hope it's clear now... – Kayan Almeida Commented Apr 17, 2015 at 14:16
Add a ment  | 

2 Answers 2

Reset to default 7

(Almost) everything is possible with Django! ;)

You just have to put your JavaScript code in a separate HTML file and then you simply include it in your main template (here: page.html) like this:

{% include 'path/to/my/template_file/js_code.html' %}

You might want to use django-js-reverse to be able to used named URL patterns in js files. You may also use the staticfiles app to manage your static assets within Django.

That will allow you to include your js files this way:

{% load static %}  {# Only load static once at the top of your file #}
<script src="{% static 'path/to/js/in/staticfiles.js' %}"></script>

And in the js file you can use:

$('#js-tag').html(Urls.home());
发布评论

评论列表(0)

  1. 暂无评论