Use of “if” in template with custom template tag with multiple arguments

廉价感情. 提交于 2019-12-02 19:21:16

问题


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' %}

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 %}

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?


回答1:


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 %}

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


来源:https://stackoverflow.com/questions/26995637/use-of-if-in-template-with-custom-template-tag-with-multiple-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!