2014-04-22 49 views

回答

0

tag上下文變量在模板中設置,而不是視圖。如果您使用內置的bootstrap3模板包,則在包含field.html的模板中定義它。如果包含模板未定義tag,則默認爲div

例如:table_inline_formset.htmlline 41

1

你可以只覆蓋標準香脆場這樣的:

class LinkField(Field): 
    def __init__(self, *args, **kwargs): 
     self.view_name = kwargs.pop('view_name') 
     super(LinkField, self).__init__(*args, **kwargs) 

    def render(self, form, form_style, context, template_pack=CRISPY_TEMPLATE_PACK): 
     if hasattr(self, 'wrapper_class'): 
      context['wrapper_class'] = self.wrapper_class 

     if hasattr(self, 'view_name'): 
      context['view_name'] = self.view_name 
     html = '' 

     for field in self.fields: 
      html += render_field(field, form, form_style, context, template=self.template, attrs=self.attrs, template_pack=template_pack) 
     return html 

然後,只需通過附加變量(「VIEW_NAME」)的重寫模板。

佈局它看起來就像這樣:

Layout(
    LinkField('field_name', template='path_to_overridden_template', 
         view_name='variable_to_pass') 
) 
1

我作爲指導palestamp的響應建立一個更通用CustomCrispyField。您可以將extra_context作爲kwarg傳遞給CustomCrispyFieldextra_context只是我從我的自定義模板中訪問的字典,我從crispy_forms中複製而來。

from crispy_forms.layout import Field 
from crispy_forms.utils import TEMPLATE_PACK 


class CustomCrispyField(Field): 
    extra_context = {} 

    def __init__(self, *args, **kwargs): 
     self.extra_context = kwargs.pop('extra_context', self.extra_context) 
     super(CustomCrispyField, self).__init__(*args, **kwargs) 

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs): 
     if self.extra_context: 
      extra_context = extra_context.update(self.extra_context) if extra_context else self.extra_context 
     return super(CustomCrispyField, self).render(form, form_style, context, template_pack, extra_context, **kwargs) 

而且我會使用它,像這樣在我的表格:

self.helper.layout=Div(CustomCrispyField('my_model_field', css_class="col-xs-3", template='general/custom.html', extra_context={'css_class_extra': 'value1', 'caption': 'value2'}) 

我的模板需要有類似於下面的代碼:

{% crispy_field field %} 
<button class="btn {{ css_class_extra }}">{{ caption }}</button> 
相關問題