问题描述
我写了一个自定义模板标签来查询数据库,并检查数据库中的值是否与给定的字符串匹配:
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
这篇关于使用& quot; if& quot;在带有多个参数的自定义模板标签的模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!