0

I have the list of objects to show on web pages(HTML file). And the type(graph, table etc.) of objects is different from the situation.

If there is a graph objects, I should load js and css files about a graph.

Because I do not want to load js, css files for graph when there is no graph object in the list, I have implemented the following jinja2 template HTML file.

{% block body %}
    {% set has_graph = 0 %}
    {% for item in components %}
        {% if item.form == 'graph' %}
            {% set has_graph = 1 %}
        {% endif %}
    {% endfor %}
    {% if has_graph == 1 %}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
    {% endif %}
{% endblock %}

I have found {% set has_graph = 1 %} worked, but the js file was not loaded.

I do not know why {% if has_graph == 1 %} does not work.

dolgom
  • 611
  • 1
  • 11
  • 27

2 Answers2

0

I found that the scope of set statement could not be beyond the loop in jinja2 document(http://jinja.pocoo.org/docs/2.9/templates/#id12).

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the following template is not going to do what you might expect:

{% set iterated = false %}
    {% for item in seq %}
        {{ item }}
        {% set iterated = true %}
    {% endfor %}
{% if not iterated %} did not iterate {% endif %}

It is not possible with Jinja syntax to do this.

dolgom
  • 611
  • 1
  • 11
  • 27
  • you can do it via imports and https://stackoverflow.com/a/16746185/533426 but yes, jinja seems to be a bit badly written – Toskan Sep 13 '17 at 10:54
0

It is true that global variables are generally not within scope inside for loops in jinja, which is a surprise to many (users of Python, Java, etc).

However, the workaround is to declare a dictionary object in that outer scope, which is then available in the for-loop:

{% set foundItem = { 'found': False } %}
    {% for item in seq %}
        {%- if item.form == "graph" %}
            {%- if foundItem.update({'found':True}) %} {%- endif %}
        {%- endif %}
    {% endfor %}
{% if not iterated %} did not iterate {% endif %}
{% if foundItem.flag %} pull in graph CSS/JS {% endif %}
CodeMantle
  • 1,249
  • 2
  • 16
  • 25