Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

python - Django Template curly brackets inside curly brackets

{% if hosts %}
    <div class="row">
        {% for host in hosts %}
            {% if host.type_of == "Backend" %}
                <div class="col-sm-3">{{ host.type_of }}</div>
               {{ headers.{{ forloop.counter0 }} }}
            {% endif %}
        {% endfor %}
    </div>
{% endif %}

I am sending arrays, hosts and headers from views to my template, I need to get element of header with the current index (getting the header[i])

Error says

Could not parse the remainder: '{{ forloop.counter0' from 'headers.{{ forloop.counter0'

Can't seem to find any examples regarding to this. How can I achieve what I want ?

question from:https://stackoverflow.com/questions/65862955/django-template-curly-brackets-inside-curly-brackets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are there an equal number of hosts and headers? If so, you could use zip(), in your view, to zip them together as follows:

headers_and_hosts = zip(headers, hosts)

Then this would allow you to do something like this in your template:

{% for host, header in headers_and_hosts %}
   {% if host.type_of == "Backend" %}
      <div class="col-sm-3">{{ host.type_of }}</div>
      {{ header }}
   {% endif %}
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...