Search code examples
djangodjango-templatesdjango-template-filterstemplatetags

Access a variable from template tag that takes arguments


I have a template tags that takes ID on template and returns a list, I want to check the list if the variable is available and make checkbox input checked.

`_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 %}.

EDIT

My custom templatetag.

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

Solution

  • I think there are a couple of ways to achieve this.

    1. From the 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

    In your case, that would be something like this:

    {% user_response question.id as user_responses %}

    1. Another approach would be to add the list in the request context, and access it from there. The downside is that this will be available in all your templates(which I guess is not what you want). See this SO answer on how to do that.

    2. Implement a Templatetag class and set the context in the render method. Here is the Django doc for how to do that: https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#setting-a-variable-in-the-context