1

After months of web-development, I find myself completely helpless trying to find a good solution for a simple problem of formatting all the numbers throughout the DOM as I wish. Specifically, I have a js function my_int_formatter(), that I want to apply to all integers after the doc has been loaded. Best descriped by example - I want to do something like

<td>my_int_formatter({{django_variable}})</td>

I know the code above won't work, because I have to include 'script' tag, but first, I don't like the messy code, and second, javascript won't recognize python variable

I tried the following way:

HTML

<td class = 'my_integer'>{{django_variable}}</td>

JS

$(document).ready(function(){
   // ....
   content = $('.my_integer').html();
   $('.my_integer').html(my_int_formatter(content));

...but as expected, I got wrong results because the js code applied the same html() content of the first .my_integer element in the DOM chain to all the others. Any ideas how to do this the short and correct way ?

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

2 Answers2

2

If I understand correctly, your problem isn't with the formatting but actualy applying the formatting to each of your dom elements.

Try using jquerys .each() function and using $(this).html() to actualy grab the content.

$('.my_integer').each(function(){
    content = $(this).html();
  $(this).html(content+"formatted");
});

here's a quick fiddle :

https://jsfiddle.net/57rdq2a0/2/

  • Starbug, I've ticked valentjedi's answer as solution because with his approach you don't have to loop through the entire DOM. I wonder, how expensive it is to loop this way, if you have large-scale site – Edgar Navasardyan Jul 07 '16 at 11:09
  • 1
    Yeah, I noticed his reply after. A lot better to do the manipulation server side (I've nerer realy touched Django so couldn't help there). Jquery's each() can be heavy on a large scale site which is why it's always better to search fo ID's rather than classes in JS. Good luck ^^ – StarbugStone Jul 07 '16 at 11:10
1

If I understand you correctly, you want to use builtin django.contrib.humanize application: https://docs.djangoproject.com/en/1.9/ref/contrib/humanize/

You can format integers using some predefined filters, for example intcomma:

4500 becomes 4,500.
45000 becomes 45,000.
450000 becomes 450,000.
4500000 becomes 4,500,000.

Usage in your case would be like

{% load humanize %}
<td>{{django_variable|intcomma}}</td>

Also don't forget to include the app in INSTALLED_APPS

Also this question might be useful

If you want to apply filter to all variables of some kind, I suggest you to use Middleware to fiddle with response before rendering.

Community
  • 1
  • 1
valignatev
  • 6,020
  • 8
  • 37
  • 61