简体   繁体   English

Django-在模板内设置变量(或在参数为函数的情况下调用IF语句)

[英]Django - Setting variable inside a template (or calling IF statement where argument is a function)

I have a (template tag - simple_tag) function, which takes 1 argument (and context) and returns a string. 我有一个(模板标签-simple_tag)函数,该函数接受1个参数(和上下文)并返回一个字符串。 So calling {% myfunction var1 %} returns a string (depended on var1). 因此,调用{% myfunction var1 %}将返回一个字符串(取决于var1)。

Now I want to use this inside a if statement, something like: {% if myfunction var1 == 'some string' %} . 现在,我想在if语句中使用它,例如: {% if myfunction var1 == 'some string' %} Obviously that doesn't work, so I have tried to firstly save returned string to a variable and then use it in if statement. 显然这是行不通的,因此我尝试首先将返回的字符串保存到变量中,然后在if语句中使用它。

But {% myfunction var1 as var2 %} doesn't work because it treats "as var2" as a second function argument and I get the "received too many positional arguments" error. 但是{% myfunction var1 as var2 %}不起作用,因为它将“ as var2”视为第二个函数参数,并且出现“接收到太多的位置参数”错误。

I have tried the "with" statement also, but it doesn't work either... 我也尝试过“ with”语句,但是它也不起作用...

So how can I save the function return value to a variable OR how can I directly use a function inside if statement ?? 那么如何将函数返回值保存到变量中,或者如何在if语句中直接使用函数呢?

You can register your template tag using django.template.Library.assignment_tag() and then use {% myfunction var1 as var2 %} in your template. 您可以使用django.template.Library.assignment_tag()注册模板标签,然后在模板中使用{% myfunction var1 as var2 %} https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags

You could make it a filter instead of a tag. 您可以将其设为过滤器而不是标签。 Then you can use it in an if statement: 然后可以在if语句中使用它:

{% if var1|myfunction == 'some string' %}

as well as just standalone: 以及独立的:

{{ var1|myfunction }}

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

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