最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

django template call javascript function on loop - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Mar 2, 2017 at 5:19 varadvarad 8,05922 gold badges67 silver badges114 bronze badges 4
  • Please post an MCVE. This bit of code you are using is something that can be done pletely without javascript – e4c5 Commented Mar 2, 2017 at 6:17
  • Yes it can be done pletely without javascript, but I need to do some processing inside javascript block so I am looking for such methods.. – varad Commented Mar 2, 2017 at 6:32
  • @e4c5 what is MCVE ? – varad Commented Mar 2, 2017 at 6:33
  • @aryan stackoverflow./help/mcve – itzMEonTV Commented Mar 2, 2017 at 6:35
Add a ment  | 

1 Answer 1

Reset to default 3

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.

发布评论

评论列表(0)

  1. 暂无评论