Reputation: 756
I want to have a custom template tag which takes two variables as arguments. This is what I have in my template:
{% load accountSum %}
{% accountSum 'account_id' 'account_type' %}
I have read that you need to load the context of these variables but I have not found a working way. So my question is, how do I define the custom template tag in templatetags/accountSum.py?
This is what I have so far:
from django import template
register = template.Library()
def accountSum(context, account_id, account_type):
account_id = context[account_id]
account_type = context[account_type]
# do something with the data
# return the modified data
register.simple_tag(takes_context=True)(accountSum)
Upvotes: 1
Views: 2109
Reputation: 20583
You have misunderstood the usage of template tags, I have read that you need to load the context of these variables
... context 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.
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 %}
Upvotes: 2