I am looping in a javascript template like:
{% for movie in movies %}
{{movie.name}}
{% endfor %}
Is there anyway like I can call a javascript function that returns required DOM element like:
{% for movie in movies %}
<script>
function get_movie(name) {
return "<div> class='movie-title'>name</div>
}
get_movie({{movie.name}})
</script>
{% endfor %}
I just want to call a js function and have some check and return an element according to..
Sure it's possible. You'd better move <script>
tag out of django loop and may be function too. Just for reference I'll put here an example from my code which draws charts in my django admin page:
<script type="text/javascript">
{% if cl.show_chart %}
(function($) {
$(document).ready(function() {
var data = [
{% for sold in cl.get_sold_info %}
{
fullname: '{{ sold.fullname }}',
date: {{ sold.date|date:"U" }}000,
partner: '{{ sold.partner }}',
price: {{ sold.price }}
},
{% endfor %} ];
draw_charts(data, $);
});
})(someNamespace.jQuery);
{% endif %}
</script>
As you can see there is some django condition inside <script>
tag, then some array is rendered with template for-loop inside some function. draw_charts
defined somewhere outside.
My advise in all these cases - move as much as you can out of places like this or your code turned into good old PHP4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With