首页 > 代码库 > django学习之模板系统

django学习之模板系统

django模板系统学习笔记之for
在for标签里面,有以下知识点:
forloop.counter
forloop.counter0
forloop.first
forloop.last
forloop.revcounter
forloop.revcounter0
froloop.parentloop
empty

下面我们举例学习:

首先到我们的工程目录下,敲入:

python manage.py shell

# forloop.counter
from django.template import Context, Template
t = Template("""
    {% for item in our_list %}
        <p>{{ forloop.counter }}: {{ item }}</p?
    {% endfor %}"""
)
c = Context({‘our_list‘: [x for x in range(10)]})
print t.render(c)

#forloop.counter0
from django.template import Context, Template
t = Template("""
    {% for item in our_list %}
        <p>{{ forloop.counter0 }}: {{ item }}</p?
    {% endfor %}"""
)
c = Context({‘our_list‘: [x for x in range(10)]})
print t.render(c)

#forloop.first
t = Template("""
    {% for object in objects %}
        {% if forloop.first %}
            <li class="first">
        {% else %}
            <li>
        {% endif %}
        {{ object }}</li>
    {% endfor %}
c = Context({‘objects‘: [x for x in range(10)]})
print t.render(c)

#forloop.last
t = Template("""
    {% for link in links %}{{ link }}{% if not forloop.last %} | {% endif %}{% endfor %}
    """)
c = Context({‘links‘: [‘link‘+ x for x in range(10)]})
print t.render(c)

#forloop.parentloop
t = Template("""
    {% for country in countries %}
    <table>
    {% for city in country.city_list %}
        <tr>
            <td>Country #{{ forloop.parentloop.counter }}</td>
            <td>City #{{ forloop.counter }}</td>
            <td>{{ city }}</td>
        </tr>
   {% endfor %}
   </table>
   {% endfor %}""")
china = {‘city_list‘: [‘shanghai‘, ‘beijing‘]}
usa = {‘city_list‘: [‘xxxx‘, ‘yyy‘]}
countries = [china, usa]
c = Context(countries)
t.render(c)


本文出自 “木子博客” 博客,请务必保留此出处http://ggbond.blog.51cto.com/8886865/1432778