Python – Passing variables to custom Django template tags

djangodjango-templatespython

I'm adding an autocomplete feature to my django application.

HTML

<script type="text/javascript"> 
            var a = {% get_fields_task_name %}
            $( "#auto_task_name" ).autocomplete({
              source: a           
            });

view

def get_fields_task_name():    
    task = Task.objects.all()    
    output = []

    for e in task:
        output.append(e.name)

    x = json.dumps(output)
    return x
get_fields_task_name = register.simple_tag(get_fields_task_name)

I need to pass parameters to get_fields_task_name, how can I do this in the template instead of {% get_fields_task_name %}?

Best Answer

This depends on exactly what the parameters are, but if it's something you can get in a single variable at template rendering time, just add it as a parameter to the function (see the docs for simple_tag).

For example:

@register.simple_tag
def get_fields_task_name(kind):
    tasks = Task.objects.filter(kind=kind)
    return json.dumps([e.name for e in tasks])

(using a list comprehension to make the function body shorter and cleaner, and also using the nicer decorator syntax).

Then you can just change the relevant line in the template to

var a = {% get_fields_task_name some_variable.kind %};