[Answered ]-Django: custom template tag which takes 2 variables

2👍

✅

You have misunderstood the usage of template tags, I have read that you need to load the context of these variablescontext is only required if you need to access/modify the existing context, not if you only need to return the calculated value from the provided arguments.

So, in your case, what you only need is this:

@register.simple_tag
def accountSum(account_id, account_type):
   # your calculation here...
   return # your return value here

Django document has a more detailed explanation and example that you can follow — Simple tags

Or, if your intention is to take the context value account_id and account_type and return a modified value on each call, you can simply omit taking the arguments, and simply do this:

@register.simple_tag(take_context=True)
def accountSum(context):
    account_id = context['account_id']
    account_type = context['account_type']
    # do your calculation here...
    return # your modified value

Then you can simply call {% accountSum %} in your template.

Or, if you want to dynamically take context content as arguments:

@register.simple_tag(take_context=True)
def accountSum(context, arg1, arg2):
    arg1 = context[arg1]
    arg2 = context[arg2]
    # calculation here...
    return # modified value...

And passing arguments in template using string like:

{% accountSum 'account_id' 'account_type' %}

I hope this helps you understand how to use template tags in your case.

updated

What I meant is this (as you don’t need to access the context, what you really need is taking arguments just like usual):

@register.simple_tag
def accountSum(arg1, arg2):
   # your calculation here...
   return # your return value here

and use this in your template:

{% accountSum account.account_id account.account_type %}

Leave a comment