【问题标题】:Why is widthratio (multiplication) not working in my template?为什么 widthratio(乘法)在我的模板中不起作用?
【发布时间】:2020-02-24 18:31:43
【问题描述】:

我正在使用 Django 2.0 和 Python 3.7。我读过我可以通过使用 widthratio - multiplication in django template without using manually created template tag 在模板中进行乘法运算。但是,在我的模板中,我尝试这样做无济于事。我在努力

 {% if widthratio articlestat.score 1 TRENDING_PCT_FLOOR >= articlestat.weighted_score %}style="font-weight:bold;"{% endif %}

当我的模板使用此代码执行时,它给出了错误...

Unused 'articlestat.score' at end of if expression.

我希望我的 if 表达式说明“articlestat.score”和“TRENDING_PCT_FLOOR”的倍数是否大于“articlestat.weighted_score”,将其打印出来,但我似乎不知道该怎么做。

【问题讨论】:

    标签: django python-3.x templates multiplication


    【解决方案1】:

    你不能在 if 这样的语句条件中使用模板标签。您可以做的是首先将widthratio 的输出分配给模板变量,然后在您的if 语句中进行比较:

    {% widthratio articlestat.score 1 TRENDING_PCT_FLOOR as ratio %}
    {% if ratio >= articlestat.weighted_score %}style="font-weight:bold;"{% endif %}
    

    【讨论】:

    • 谢谢,但我仍然看到一些奇怪的结果。 “widthratio”不处理浮点数吗?这 {% widthratio .3 1 .9 as answer %} 产生“答案”= 0,这是不正确的,不是我想要的。
    • 它确实处理浮点数,但它rounds the result 到最接近的整数。它主要用于计算图像宽度比,可能不适合您想要的。我认为您实际上最好只使用writing your own template tag 来处理您的逻辑。
    • 嗯,好吧,在我还是 Django 的新手之前,我认为我不需要编写自己的自定义标签来进行乘法运算。也许我错了。我会到处谷歌。
    • Django 关于在模板中应该/不应该做什么的理念是documented here“如果您有编程背景,或者如果您习惯于将编程代码直接混合到 HTML 中的语言,您需要记住 Django 模板系统不仅仅是将 Python 嵌入到 HTML 中。这个是设计使然:模板系统旨在表达演示,而不是程序逻辑。”(链接中还有更多内容)。
    【解决方案2】:

    我习惯于仅将模板标签用于纯模板问题(例如将数字格式化为美元)并将所有逻辑留给模型(如果逻辑是特定于模型的)或视图(如果它是业务逻辑或依赖你在什么观点)。

    当 TRENDING_PCT_FLOOR 为静态时,将向articlestat 模型添加属性,而不是使用自定义模板标记:

    class ArticleStat(models.Model):
    
        TRENDING_PCT_FLOOR = x
    
        @property
        def is_ratio_positive(self):
            ratio = self.score * self.TRENDING_PCT_FLOOR
            return ratio >= self.weighted_score 
    

    然后在模板上,我会使用:

    {% if articlestat.is_ratio_positive %}style="font-weight:bold;"{% endif %}
    

    如果 articlestat 不是模型(例如它是在 views.py 上创建的),那么我将在相应视图上使用上述逻辑。

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2015-02-16
      相关资源
      最近更新 更多