How to pass multiple arguments to a template tag with multiple "as" arguments in Django Template?

349 Views Asked by At

With @register.simple_tag, I defined the custom tag test() which has 2 parameters as shown below:

from django.template import Library

register = Library()

@register.simple_tag
def test(first_name="John", last_name="Smith"):
    return first_name + " " + last_name

Then, I pass "Anna" and "Miller" to test() with two as arguments in Django Template as shown below:

{% test "Anna" as f_name "Miller" as l_name %}
{{ f_name }} {{ l_name }}

But, there is the error below:

django.template.exceptions.TemplateSyntaxError: 'test' received too many positional arguments

Actually, there is no error if I pass only "Anna" to test() with one as argument as shown below:

{% test "Anna" as f_name %}
{{ f_name }}

Output:

Anna Smith

And, there is no error if I pass "Anna" and "Miller" to test() without as arguments as shown below:

{% test "Anna" "Miller" %}

Output:

Anna Miller

So, how can I pass multiple arguments to a template tag with multiple as arguments in Django Template?

1

There are 1 best solutions below

0
Super Kai - Kazuya Ito On

as argument can store the return values from the template tag test() according to the doc below in 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:

And according to my experiments, it is impossible to pass multiple arguments to a template tag with multiple as arguments in Django Template.

But, you can pass multiple arguments to a template tag with only one as argument in Django Template as shown below:

{% test "Anna" "Miller" as full_name %}
{{ full_name }}

Output:

Anna Miller