我想用 django 计算模板中的百分比
I want to calculate percentage in template with django
我想计算并显示模板中产品的折扣利息。我尝试了类似下面的方法,但没有用。有实用的方法吗?
index.html
{% if product.sale %}
<span class="sale">{{((product.price - product.sale) / product.price) * 100}}</span>
{% endif %}
你没有。这样的逻辑不属于模板。 Django 的模板语言是故意限制以防止人们在模板中编写此逻辑。
通常你在模型中写这个,例如作为一个属性,比如:
class Product(models.Model):
# …
<strong>@property</strong>
def <b>price_percentage</b>(self):
return 100 * (self.price - self.sale) / self.price
然后在模板中您可以将其呈现为:
{% if product.sale %}
<span class="sale">{{ product.price_percentage }}</span>
{% endif %}
我想计算并显示模板中产品的折扣利息。我尝试了类似下面的方法,但没有用。有实用的方法吗?
index.html
{% if product.sale %}
<span class="sale">{{((product.price - product.sale) / product.price) * 100}}</span>
{% endif %}
你没有。这样的逻辑不属于模板。 Django 的模板语言是故意限制以防止人们在模板中编写此逻辑。
通常你在模型中写这个,例如作为一个属性,比如:
class Product(models.Model):
# …
<strong>@property</strong>
def <b>price_percentage</b>(self):
return 100 * (self.price - self.sale) / self.price
然后在模板中您可以将其呈现为:
{% if product.sale %} <span class="sale">{{ product.price_percentage }}</span> {% endif %}