“如果"的使用在带有多个参数的自定义模板标签的模板中 [英] Use of "if" in template with custom template tag with multiple arguments
问题描述
我编写了一个自定义模板标签来查询我的数据库并检查数据库中的值是否与给定的字符串匹配:
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 文档: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
这篇关于“如果"的使用在带有多个参数的自定义模板标签的模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!