2016-08-18 4 views
0

フィールド名からテンプレートタグに複数の変数を送信できるかどうかは誰にでも分かりますか?Djangoテンプレートは、テンプレートタグに2つの引数を送りますか?

この質問How do I add multiple arguments to my custom template filter in a django template?はほとんどありますが、文字列として2つのフィールド名を送信する方法はわかりません。

私のテンプレート:

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

上記のdidntの仕事

私のテンプレートタグ:

@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 

答えて

1

私の視点から、それは簡単なタグの代わりにテンプレートを使用する方が簡単になりますフィルタを使用して、文字列を送信することなく呼び出すことができます。

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

あなたのテンプレートは、ちょうど次のようになります。

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

とテンプレートタグは次のようになります。簡単なタグを認識して

@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 
+0

波平!しかし、単純なタグを使用するとエラーが発生する... " 206行目に無効なブロックタグがあります: 'remaining_cost'、 'elif'、 'else'または 'endif'が必要です。私は忘れてしまった \t \t \t​​{%remaining_cost item.cost_per_month item.install_date item.comtract_length%} – AlexW

+0

申し訳ありません。あなたはすでにそのうん、ハイテクテンプレート –

+0

を配置する必要があります既に追加されていますが、私はいくつかの他のフィルタを同じ.pyにロードしています。 –

関連する問題