2012-01-10 6 views
3

私が使用していることを実感:ジャンゴ変数 - ベストプラクティス

... 
return render_to_response('mytemplate.html', { 
     'some_variable' : some_variable, 
     'some_list': some_list, 
}, context_instance=RequestContext(request)) 

その読みやすさと明示のためのより良いと考えられている:

... 
return render_to_response('mytemplate.html', 
locals(), context_instance=RequestContext(request)) 

をビューにするような良いコードと何かが考慮されていません。私は、返されるかもしれない、あるいは返されないかもしれない変数をどう扱うのが最も好奇心であったのです。

... 
some_variable = None 
some_variable = <some business logic> 
return render_to_response('mytemplate.html', { 
     'some_variable' : some_variable, 
     'some_list': some_list, 
}, context_instance=RequestContext(request)) 

このようなビューで明示的に設定すると、表示コードが長くなることがあります。あるいは、応答にそれらを含める前に変数の存在をチェックすべきですか?私は何もしない場合はもちろん

は、私が取得:

local variable 'some_variable' referenced before assignment 

任意の提案を歓迎しました。

+0

最初の例では何が問題になっていますか? – Marcin

+1

@Marcin:それはしばしば文脈の汚染をもたらす、怠け者で控えめなコードです。それは*働いていますが、非常にうまくいかないものです。 –

+0

@ChrisPratt:怠惰で汚いという意味は、「私はそれが好きではありません」という意味です。問題は、テンプレートで使用されていない多くの地元の人がいるビューでのみコンテキストの汚染ですか、それとも何か問題がありますか? – Marcin

答えて

2

中間の方法は、コンテキスト辞書自体をスタックとして使用することです。

context = {} 
if <condition>: 
    context['cond1'] = 'foo' 

if <condition2>: 
    context['cond2'] = 'bar' 

return render_to_response('template.html', context) 

(また、Djangoの1.3以来、あなたの代わりにlongwinded context_instance=RequestContextもののrender(request, template, context)を使用できることに注意してください。)

+1

もちろん、彼が1.3を使用している場合は、クラスベースのビューを使用する方が良いでしょう。 ;) –

+0

私は 'render(request、template、context)'を使ってみました。これは期待通りに動作しているようですが、 'context' [some_variable ']'と 'render'呼び出しに変数の辞書がありません。これは古い方法と同じようにはっきりと読み取れるか? –

2

どちらかつまり、条件付きであなたのコンテキストを構築:

context = { 'some_list': some_list } 

... 

if <something>: 
    context['some_variable'] = some_variable 

... 

return render_to_response('mytemplate.html', context, context_instance=RequestContext(request)  

または適切なデフォルト値を使用します。

return render_to_response('mytemplate.html', { 
    'some_variable' : some_variable or 'Default', 
    'some_list': some_list, 
}, context_instance=RequestContext(request)) 
+0

2番目の方法の簡潔さは、条件文の損失とは異なり、コードの長さにあまり影響を与えないので好きです。おそらくこの方法の不利な点はありますか? –

+1

実際には、これは私のためには機能しません。 'some_variable 'を設定した場合、私はまだ' local variable' some_variable 'assignment' errorの前に参照されます:some_variableまたはNone、 '' –

関連する問題