在此使用“ if”。在带有多个参数的自定义模板标签的模板中
我编写了一个自定义模板标签来查询数据库,并检查数据库中的值是否与给定的字符串匹配:
I wrote a custom template tag to query my database and check if the value in the database matches a given string:
@register.simple_tag
def hs_get_section_answer(questionnaire, app, model, field, comp_value):
model = get_model(app, model)
modal_instance = model.objects.get(questionnaire=questionnaire)
if getattr(modal_instance, field) == comp_value:
return True
else:
return False
在我的模板中,可以按以下方式使用此标记:
In my template I can use this tag as follows:
{% hs_get_section_answer questionnaire 'abc' 'def' 'ghi' 'jkl' %}
该函数正确返回True或False。
The function returns True or False correctly.
我的问题:我想执行以下操作:
My problem: I'd like to do something like this:
{% if hs_get_section_answer questionnaire 'abc' 'def' 'ghi' 'jkl' %}
SUCCESS
{% else %}
FAILURE
{% endif %}
但这是行不通的;似乎 if模板标记无法处理多个参数。
But this does not work; it seems as if the "if" template tag cannot handle multiple arguments.
有人可以提示我如何解决此问题吗?
Can anybody give me a hint how to solve this problem?
将模板标签调用的结果设置为变量,然后对该结果调用{%if%}
Set the result of the template tag call to a variable then call {% if %} on that result
{% hs_get_section_answer questionnaire 'abc' 'def' 'ghi' 'jkl' as result %}
{% if result %}
...
{% endif %}
您还需要更改模板标记以使用分配标签,而不是简单的标签。请参阅任务标签django doc: https:// docs。 djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags
You will also need to change your template tag to use an assignment tag instead of a simple tag as well. See assignment tags django doc: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags
@register.assignment_tag
def hs_get_section_answer(questionnaire, app, model, field, comp_value):
model = get_model(app, model)
modal_instance = model.objects.get(questionnaire=questionnaire)
if getattr(modal_instance, field) == comp_value:
return True
else:
return False