amankarn
amankarn

Reputation: 71

how to pass template variables to javascript

Friends, I am trying to pass the template variable to javascript in order to create a chart. But I am not getting it. Django considers all js files as static files. So dynamic template variables aren't available to javascripts.

I even tried this:

passing template variables to javascript

But it didn't help either. Only one variable could be passed. The rest didn't.

def profile(request,username):
    try:
        u = User.objects.get(username=username)
        questions = Question.objects.filter(user=u)
        answers = Answer.objects.filter(user=u)
        docs = Document.objects.filter(user=u)
    except User.DoesNotExist:
        pass
    return render(request,"auths/profile.html",locals())

Also, as described in the above link, my profile.html is

<input type="hidden" value="{{ u.username }}" id="username" />
<input type="hidden" value="{{ docs.count }}" id="docs" />
<input type="hidden" value="{{ questions.count }}" id="questions" />
<input type="hidden" value="{{ answers.count }}" id="answers" />


{% block extra %}
    <script type="text/javascript">
        var user = document.getElementById("username").value;
        var docs = document.getElementById("docs").value;
        var questions = document.getElementById("questions").value;
        var answers = document.getElementById("answers").value;
    </script>

   <script type="text/javascript" src="{% static 'highcharts.js'%}">      </script>
   <script type="text/javascript" src="{% static 'highcharts-3d.js'%}"></script>

   <script type="text/javascript" src="{% static 'chart.js' %}"></script>


{% endblock %}

And a section of my chart.js where I pass the data is :

series: [{
  type: 'column',
  name: 'User Profile',
  data: [
      ['Questions',   questions],
      ['Answers',   answers],
      ['Documents',  docs]
  ]
}]

As explained earlier, the problem is only one variable gets passed while the rest don't. As a result, no chart is rendered. What should I do friends?

In case if it helps, I am using Django 1.9 and highcharts.

Upvotes: 1

Views: 302

Answers (1)

amankarn
amankarn

Reputation: 71

To answer my own question, I think I figured out what was wrong. The chart values are in number format. But I was passing it as string. So all that was needed to be done is convert those strings into values or number using javascript typecasting.

And a section of my chart.js where I pass the data is :

series: [{
  type: 'column',
  name: 'User Profile',
  data: [
      ['Questions',   Number(questions)],
      ['Answers',   Number(answers)],
      ['Documents',  Number(docs)]
      ]
}]

Changing the strings into numbers, the chart was rendered!

Upvotes: 2

Related Questions