Why is widthratio (multiplication) not working in my template?

Viewed 1094

I'm using Django 2.0 and Python 3.7. I've read I can do multiplication in templates by using widthratio -- multiplication in django template without using manually created template tag . However, in a template of mine, I'm trying this to no avail. I'm trying

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

When my template is executed with this code, it gives the error ...

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

I want my if expression to say if the multiple of "articlestat.score" and "TRENDING_PCT_FLOOR" is greater than "articlestat.weighted_score," print this out, but I can't seem to figure out how to do that.

2 Answers

You can't use template tags inside if statement conditionals like that. What you can do is first assign the output of widthratio to a template variable, and then compare that in your if statement:

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

I have the habit of using template tags only for pure templating questions (e.g. formating a number to dollars) and leaving all logic to the models (if the logic is model-specific) or views (if it's a business logic or depends on what view you're in).

Instead of using a custom template tag, would add a property to the articlestat model when TRENDING_PCT_FLOOR is static:

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 

Then on the template, I would use:

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

If articlestat is not a model (e.g. it was created on views.py) then I would use the logic above on the corresponding view.

Related