Django/JavaScript: how to share code between the two?
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:
- With JavaScript enabled, it uses jQuery autocomplete on an input field, and generates a table of results on autocomplete, all in client-side JavaScript.
- 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开发者_如何学JAVA 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!
you can pass json to client, and then render it with some client-side templating engine. for example JQuery templating engines
精彩评论