Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

python - 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  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...