Reputation: 63
I have tried the if condition based on the value defined in the django template
{% if randomgen == 2 %}
<p style="float:right;text-align: center;padding:5px 5px;"><b>{% randomgen %}1</p>
{% else %}
<p style="float:right;text-align: center;padding:5px 5px;"><b>{% randomgen %} 2</p>
{% endif %}
the randomgen is defined to pick in random between 1 and 2 and the value is being displayed correctly in
tag but irrespective of the value it always going to else condition
register = template.Library()
@register.tag(name="randomgen")
def randomgen(parser, token):
items = []
bits = token.split_contents()
for item in bits:
items.append(item)
return RandomgenNode(items[1:])
def render(self, context):
arg1 = 0
arg2 = 10
if "float" in self.items:
result = random.randint(1,20)
elif not self.items:
result = random.randint(1,20)
else:
result = random.randint(1,2)
return result
Upvotes: 4
Views: 1229
Reputation: 84
In your HTML, set randomgen
to another variable:
{% randomgen as rgen %}
Then use the newly set variable for your conditional:
{% if rgen == 2 %}
Honestly, I was surprised your code didn't work as your usage makes sense intuitively. Knowing that it doesn't work though, my guess is the template is comparing a function with an integer which is always going to return False. Good question!
Upvotes: 3