Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template, send two arguments to template tag?

Can anyone tell me if its possible to send multiple variables from field names to a template tag?

this question How do I add multiple arguments to my custom template filter in a django template? is almost there, but i dont know how to send my two field names as a string.

my template:

    <th>{{ item.cost_per_month|remaining_cost:item.install_date + ',' + item.contract_length }}</th>

the above didnt work

my template tags:

@register.filter('contract_remainder')
def contract_remainder(install_date, contract_term):
    months = 0
    now = datetime.now().date()
    end_date = install_date + relativedelta(years=contract_term)

    while True:
        mdays = monthrange(now.year, now.month)[1]
        now += timedelta(days=mdays)
        if now <= end_date:
            months += 1
        else:
            break
    return months    

@register.filter('remaining_cost')
def remaining_cost(cost_per_month, remainder_vars):
    dates = remainder_vars.split(',')
    cost = contract_remainder(dates[0], dates[1]) * cost_per_month
    return cost  
like image 453
AlexW Avatar asked Aug 18 '16 14:08

AlexW


1 Answers

From my point of view it looks easier to use a simple tag instead of a template filter so you can call it without needing to send a string.

https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#simple-tags

Your template would be just:

{% load remaining_cost %}
{# Don't forget to load the template tag as above #}

<th>{% remaining_cost item.cost_per_month item.install_date item.comtract_length %}</th>

and the template tag would be:

@register.simple_tag
def remaining_cost(cost_per_month, install_date, contract_length):
    cost = contract_remainder(install_date, contract_length) * cost_per_month
    return cost 
like image 130
Daniel Schwarze Avatar answered Nov 07 '22 21:11

Daniel Schwarze