在jjango模板中嵌入javascript代码

Enr*_*ueH 1 javascript django highcharts

基于此Highcharts示例(HTML中包含的javascript代码):http://jsfiddle.net/f4Ef7/

我有一个模板,我想嵌入JavaScript代码,而不必包含任何静态.浏览器正在处理与JS无关的任何内容.目前我的views.py看起来像:

# -*- encoding: utf-8 -*-

from django.shortcuts import render
from django.http import HttpResponse
from tfgplot.models import estado_foneras
from django.template import RequestContext, loader
def index(request):
    template = loader.get_template('tfgplot/index.html')
    context = RequestContext(request)
    return render(request, 'tfgplot/index.html', context)
Run Code Online (Sandbox Code Playgroud)

我的应用程序名为tfgplot,模板index.html如下所示:

<div id="container" style="min-width: 300px; height: 300px; margin: 1em">
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<head></head>
<body>
<div>
<script type="text/javascript">
{% autoescape off %}
    $('#container').highcharts({
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        series: [{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }]

    });
{% endautoescape %}
</script>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)

这应该创建一个可以在链接中看到的图形,但我无法看到我期待的图形,任何想法?

eca*_*ver 5

首先,你的HTML非常混乱,这里有几件事:

  1. 每个div或几乎任何其他html标记应该驻留在body标记内.
  2. 您应该在head标记内或标记末尾加载脚本body.
  3. 您应该等到DOM准备好创建图表或执行任何其他JavaScript工作.
  4. 你需要jQuery为了$('#container')工作.
  5. divcontainer必须关闭的元素.
  6. 您不应该css直接向html元素添加样式.而是在一个单独的文件中(类似的东西styles.css).
  7. 没有必要让你script进入div,你可以摆脱它.

这是一个应该做你想要的代码:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <script src="http://code.highcharts.com/modules/exporting.js"></script>
  </head>
  <body>
    <div id="container" style="min-width: 300px; height: 300px; margin: 1em">
    </div>
    <script type="text/javascript">
      {% autoescape off %}
      $(document).ready(function(){
          $('#container').highcharts({
              xAxis: {
                  categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
              },
              series: [{
                  data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
              }]
          });
      });
      {% endautoescape %}
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

有关html/css标准的更多信息,请查看谷歌的链接.

此外,由于您正在使用django,因此您需要了解模板继承.如果上述代码不起作用,请共享更多代码和/或错误信息.