0

I want to use template variable inside JavaScript : My problem is using for loop inside the javascript code is every thing between for loop is going to repeat .. But i don't want that....Below i have pasted my code ..Can anybody tell me the better way of doing this....because this looks ugly..

Here is my code:

    {% block extra_javascript %}
    <script src="/static/js/Chart.min.js"></script> 
    <script>    
    $(document).ready(function(){
        var data = {
    labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
    datasets : [
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",

                      data : [{{ stats_dict.0.Jan }},{{ stats_dict.1.Feb }},{{ stats_dict.2.March }},{{ stats_dict.3.April }}
                      ,{{ stats_dict.4.May }},{{ stats_dict.5.June }},{{ stats_dict.6.July }},{{ stats_dict.7.August }},{{ stats_dict.8.Sept }},
                      {{ stats_dict.9.Oct }},{{ stats_dict.10.Nov }},{{ stats_dict.11.Dec }}]                     


        }
    ]
};
    //Get context with jQuery - using jQuery's .get() method.
    var ctx = $("#myChart").get(0).getContext("2d");
    //This will get the first returned node in the jQuery collection.
    var myNewChart = new Chart(ctx).Bar(data,{});
    });
  </script>
  {% endblock %}

Context :

[[{'stats_dict': [{'Jan': 0}, {'Feb': 0}, {'March': 0}, {'April': 0}, {'May': 0}, {'June': 0}, {'July': 0}, {'August': 0}, {'Sept': 3}, {'Oct': 0}, {'Nov': 0}, {'Dec': 0}]}], {'csrf_token': <django.utils.functional.__proxy__ object at 0xa4d874c>}, {'perms': <django.contrib.auth.context_processors.PermWrapper object at 0xa4d878c>, 'user': <django.utils.functional.SimpleLazyObject object at 0xa47abcc>}, {}, {'LANGUAGES': (('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('eo', 'Esperanto'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('kk', 'Kazakh'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nb', 'Norwegian Bokmal'), ('ne', 'Nepali'), ('nl', 'Dutch'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('sw', 'Swahili'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('tt', 'Tatar'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese')), 'LANGUAGE_BIDI': False, 'LANGUAGE_CODE': 'en-us'}, {'MEDIA_URL': ''}, {'STATIC_URL': '/static/'}, {'TIME_ZONE': 'America/Chicago'}, {'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0xa47ac6c>}]
2
  • I'm not sure I understand what is inside stats_dict. Could you show the Python that gives it context, or show it printed out? Commented Sep 8, 2013 at 11:47
  • I want know better way of doing what i have done above....If i use for loop to get the stats_dict value the whole java script will repeat 12 time and i don't want that .... Commented Sep 8, 2013 at 11:56

1 Answer 1

3

Step 1 - Never EVER mix JavaScript and Django template language. It's a setup for disaster.

Step 2 - Refactor

Refactor first step:

Create a new view that outputs a JSON'd dict of dates. (I'm not coding your application but I'll give you the pointers on how to improve)

def date_view(request):
    stats = Stats.objects.all().order_by('month')
    #do some other stuff that you already have done.
    return {'january':stats.january, and so forth...}

Step b) - Refactor your current code to something along the lines of this:

var dataForChart =  {
  labels: [months],
  datasets: [{
    fillColor: ...,
    strokeColor: ...,
    data: null,
  }]
}

$.get('/myStatsViewUrl', function(data) {
  dataForChart["data"] = data;
});

Step c) Rejoice that you now have decoupled Djangos template from your javascript and much rejoicing was done 'cause you can now reuse it anywhere in your code!

Sign up to request clarification or add additional context in comments.

2 Comments

You could use rest-framework for serialized views
@kroolik Yeah, definately, but I don't think it's the best idea for his issues atm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.