Adding conditions to <script src=..> in html using django

html:

 <body>
    <script>
        var participants =[];
    </script>
    {% for player in playerList %}
        ...........
        {% empty %}
            <div style="text-align: center; color: Black; margin-bottom: 90%">
                <h2>empty</h2>
            </div>
    {% endfor %}

    <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}"></script>

    </body>

I want want to stop the execution of <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}"> part when participants =[] is empty. How to do that?.

Upvotes: 1

Views: 85

Answers (2)

Matt Cremeens
Matt Cremeens

Reputation: 5151

I am pretty sure you are using the django template language. If so, please tag as such. You can check the length of your list using |length. So do this

{% if playerList|length > 0 %}
    <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}">
{% endif %}

if you only want to include this script when participants is populated. Or you could simply do this

{% if playerList %}
    <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}">
{% endif %}

I believe, but the first one is more explicit and, in my opinion, easier to know what is happening.

Upvotes: 1

Muhammad
Muhammad

Reputation: 7324

If you mean JavaScript in browser then you can do something.

<body>
<script>
    var participants =[];
</script>
{% for player in playerList %}
    ...........
    {% empty %}
        <div style="text-align: center; color: Black; margin-bottom: 90%">
            <h2>empty</h2>
        </div>
{% endfor %}

<script>
(function() {
   if(participants.length){
    document.write('<script src="{% static 'event-management-system/js/index.js' %}"><\/script>');
   }
})();
</script>

</body>

Upvotes: 0

Related Questions