2011-10-12 65 views
1

以下情況下的最佳方法是什麼?模型中的通用模板或模板 - Django

假設我們有一些模型,例如Article,Photo,BlogEntry等。每個模型都可以作爲拇指或所謂的小部件顯示在頁面上。

實施例:一個模型的

  • 屬性thumbview包含項拇指與HTML塊標題
  • normalview - 包含在一個塊
  • bigview大拇指,標題和描述 - 拇指,標題,說明並說...評論添加數量

所有這些應該是在某種模式多態的模板Ë所以我可以做這樣的事情在我的抽象項目(各種類型)和簡單的列表迭代:

{{ item.thumbview }} 

{{ item.bigview }} 

顯示每個項目的拇指。

它可以在模型中實現懶惰評估,但我不覺得在模型中硬編碼html是正確的方法。

我該如何建模這樣的行爲?什麼是最好的方法?

我將不勝感激任何建議。謝謝。

回答

1

您可以使用自定義模板標籤和標準方法的模型給一個上下文的情況下,小部件無法達到在模板中的一些屬性:

myapp/models.py

class Photo(models.Model): 
    ... 
    def widget_context(self, context): # receives the context of the template. 
     user = context['request'].user # context should be RequestContext to contain request object (or you may use thread locals). 
     return {'tags': self.tag_set.filter(...), 'can_edit': self.owner == user or user.is_admin} 

模板標籤文件,widgets_app/templatetags/objwidgets.py

@register.simple_tag(takes_context=True) 
def object_widget(context, obj, size='small'): 
    context_func = getattr(obj, 'widget_context') # try getting the context method 
    extra_context = context_func(context) if context_func else {} 
    extra_context['obj'] = obj 

    long_tuple = (obj._meta.app_label, 'widgets', obj.__class__.__name__, size) 
    return render_to_string([ # multiple templates to have both generic and specific templates 
     '%s/%s/%s.%s.html' % long_tuple, # the most specific (photos/widgets/photo.small.html) 
     '%s/widget.%s.%s.html' % (obj._meta.app_label, obj.__class__.__name__, size), 
     '%s/widget.%s.html' % (obj._meta.app_label, size), # myapp/widget.small.html 
     'widget.%s.html' % size, 
    ], 
    extra_context 
    context) 

用法:

{% load objwidgets %} 
{% object_widget photo1 'large' %} 
{% object_widget photo2 %} 

使該對象控件模板,myapp/widgets/photo.small.html

<b>{{ obj.name }}</b> 
<img src="{{ obj.thumbnail.url }}"/> 
{% if can_edit %}<a href="{{ obj.get_edit_url }}">edit</a>{% endif %} 
{% for t in tags %} 
    <a href="{{ tag.get_absolute_url }}">{{ tag.text }}</a> 
{% endif %} 
+0

很好的解釋。非常感謝你! – laszchamachla

+0

不客氣! –

+0

_編碼幾天後 - 這種方法簡直太棒了!它非常鼓勵DRY,使開發更快更清潔。對我來說最好的Django建議:) – laszchamachla

0

你不應該在你的模型中生成html。你可以寫some custom template tags來實現你所需要的。如果您使用的是django dev版本,您可以創建一個包含標籤,其中包含一個可以根據輸入的模型類型返回一段html的參數。