简体   繁体   English

如何在django项目的html模板中创建局部变量?

[英]How to create a local variable in a html template in django project?

I am a beginner to python and django. 我是python和django的初学者。 Here I am trying to build a website. 在这里,我正在尝试建立一个网站。

I have created a class named cluster which actually mean a town or city. 我创建了一个名为cluster的类,它实际上意味着一个城镇或城市。 As a subclass I have created schools for cluster. 作为一个子类,我为集群创建了学校。 Schools have a field school_strength to get strength for each school. 学校有一个字段school_strength得到强度为每所学校。 Now I have to display the total strength of all the schools that belong to each cluster. 现在我必须显示属于每个群集的所有学校的总体力量。

This is how I am trying to do that in html template for cluster details by creating a local variable strength to calculate sum from all schools. 这就是我在html模板中尝试通过创建局部变量强度来计算所有学校的总和的方法。

<div class="col-sm-4 col-md-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <a href="{% url 'music:cluster_detail' state.id region.id cluster.id %}">
                    {% if cluster.cluster_logo %}
                        <img src="{{ cluster.cluster_logo.url }}" class="img-responsive">
                    {% else %}
                        <h3>No image to display</h3>
                    {% endif %}
                </a>
                <h2>{{ cluster.cluster_name }}</h2>
                <h4>{{ cluster.cluster_coordinator }}</h4>
                <h4>{{ cluster.cco_number }}</h4>
                <h4>{{ cluster.cco_email }}</h4>
                {% for school in cluster.school_set.all %}
                    {% strength = strength + school.school_strength %}
                {% endfor %}
                <h4>{{ strength }}</h4>
            </div>
        </div>
    </div>

I think you can declare the variable with with tag. 我想你可以使用with标签来声明变量。 But that will not work the the way you want it to work . 但这不会按照您希望的方式工作 Below is an example to it. 下面是一个例子。

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

So, the better way is you can store it in a variable in views.py and pass it to html template. 因此,更好的方法是将它存储在views.py中的变量中并将其传递给html模板。

views.py views.py

strength=0
for school in cluster.school_set.all():
     strength = strength + school.school_strength

context['strength']=strength

return render(request, 'template/html`, context)

html HTML

<h3>Strength Of Cluster: {{strength}}</h3>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM