从带参数的模板标签访问变量

Access a variable from template tag that takes arguments

我有一个带有模板 ID 的模板标签和 returns 一个列表,我想检查列表是否可用变量并选中复选框输入。

`_checkbox.html`
{% load get_previous_response %}

{% user_response question.id %} {# this returns a list of ids #}

So I want to do something like this

<input type="checkbox" {% if option.id in user_response %}checked{% endif %}>
problem is the above won't work, I tried django templatetag `with template context`

My main goal is I want to access the list returned by {% user_response question.id %}.

编辑

我的自定义模板标签。

get_previous_response.py

from django import template
from survey.models import Question
register = template.Library()

@register.simple_tag(takes_context=True)
def user_response(context, question_id):
    question = Question.objects.filter(id=question_id).first()
    user = context['request'].user
    response = question.get_simple_answer(user)
    return response

你可以试试:

{% if option.id in user_response %}
   <input type="checkbox" checked>
{% else %}
   <input type="checkbox">
{% endif %}

我认为有几种方法可以实现这一目标。

  1. 来自django docs on simple tags:

It’s possible to store the tag results in a template variable rather than directly outputting it. This is done by using the as argument followed by the variable name. Doing so enables you to output the content yourself where you see fit

在你的情况下,应该是这样的:

{% user_response question.id as user_responses %}

  1. 另一种方法是在请求上下文中添加列表,然后从那里访问它。缺点是这将在您的所有模板中可用(我想这不是您想要的)。 请参阅此 了解如何做到这一点。

  2. 实现一个模板标签class并在渲染方法中设置上下文。这是有关如何执行此操作的 Django 文档:https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#setting-a-variable-in-the-context