Wednesday, May 18, 2022

[FIXED] how to include a template n times in django?

Issue

I would like to include a partial n times in a django app (I am new to/learning django). I am more experienced in rails, where I would simply write:

 <% 3.times do %>
    render 'feeds/feature'
 <% end %>

I would like to know how to do something similar in django. Here is what I thought to do:

 {% i = 1%}
 {% for i =< 9 %}
   {% include 'feeds/feature.html'%}
   {% i += 1%}
 {% end %}

This, however, does not work - i get a template syntax error Invalid block tag: 'i', expected 'endblock'

Can I embed python into a django page like I do in rails? And, more importantly, how would I include the feature.html page n (or in this case 9) times in django?


Solution

Just put range in the context from the view and then:

In the view:

render_to_response('foo.html', {..., 'range': range(9), ...}, ...)

In the template:

{% for i in range %}
    {% include 'feeds/feature.html'%}
{% endfor %}

Also you can do something like that:

{% for i in "123456789" %}
    {% include 'feeds/feature.html'%}
{% endfor %}

Yes, very ugly.

Or you can define template tag:

Snipet 1

Snipet 2



Answered By - Vladislav Mitov
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.