1

I've got a Django application that makes heavy use of JavaScript, and I want to know the best practice for sharing code between the two.

Specifically, I have a page that works both with and without JavaScript:

  1. With JavaScript enabled, it uses jQuery autocomplete on an input field, and generates a table of results on autocomplete, all in client-side JavaScript.
  2. With JavaScript, if you type into the input field and submit the form, the same table of results is returned, as a Django view/template.

To do this, I'm duplicating quite a lot of code: both the static HTML table header/footer, and also the code for each row, generated using a for loop. (In pseudocode: for result in results: output '<td>result.title</td><td>result.author</td>' etc.)

How can I avoid duplicating this code, and instead share it nicely between Django and JavaScript?

Thanks!

AP257
  • 89,519
  • 86
  • 202
  • 261

1 Answers1

0

you can pass json to client, and then render it with some client-side templating engine. for example JQuery templating engines

Community
  • 1
  • 1
Valentin Kantor
  • 1,799
  • 1
  • 23
  • 27
  • thanks, but how do I use this on my non-JavaScript pages? should I ask the Django to pull in data from a JSON page somehow? – AP257 Mar 02 '11 at 11:06
  • hm, you can try use custom template tags, so in your template it will looks like this: {{ my_obj|as_table }}, but you still need to do all parsing work, to place your results in table.. [link]http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ – Valentin Kantor Mar 02 '11 at 21:53