Django Template - New Variable Declaration

后端 未结 4 1683
感动是毒
感动是毒 2020-12-31 09:06

Let me preface by I am just starting Python so if this is really a simple question ^_^

I have a html file with the following content:

        {%for d         


        
相关标签:
4条回答
  • 2020-12-31 09:45

    this is how to do it:

    {% with name="World" greeting="Hello" %}     
    <html>
    <div>{{ greeting }} {{name}}!</div>
    </html>
    {% endwith %}
    

    see also: with tag

    by john and yarden from this post: How to set a value of a variable inside a template code?

    0 讨论(0)
  • 2020-12-31 09:52

    In template:

    {% for outer_obj in outer_list %}
        {% for inner_obj in inner_list %}
             {% increment_counter forloop.counter0 forloop.parentloop.counter0 outer_list.count %}
        {% endfor %}
     {% endfor %}
    

    Templatetag:

    @register.simple_tag
    def increment_counter(outer, inner, outer_loop_length):
        return outer + inner * outer_loop_length + inner * (outer_loop_length - 1)
    

    Result: 0 1 2 3 ...

    0 讨论(0)
  • 2020-12-31 10:02

    Check out the documentation on the for loop.

    It automatically creates a variable called forloop.counter that holds the current iteration index.

    As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the add filter. Likewise, you can create your own filters just like with tags.

    0 讨论(0)
  • 2020-12-31 10:07

    If you want to set any variable inside a Django template, you can use this small template tag I've written.

    0 讨论(0)
提交回复
热议问题