Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template call javascript function on loop

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..

like image 236
varad Avatar asked Oct 29 '22 11:10

varad


1 Answers

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.

like image 185
valignatev Avatar answered Nov 13 '22 16:11

valignatev