2017-08-28 119 views
1

目前,我有近两个完全一样的模板,它们使用相同的Django的形式,但只有1个参数的变化以这两种形式是操作方法,那就是如何重用Django模板?

Django的形式

class DropDownMenu(forms.Form): 
    week = forms.ChoiceField(choices=[(x,x) for x in range(1,53)] 
    year = forms.ChoiceField(choices=[(x,x) for x in range(2015,2030)] 

模板1

<form id="search_dates" method="POST" action="/tickets_per_day/"> 
    <div class="row"> 
     <div style="display:inline-block"> 
      <h6>Select year</h6> 
       <select name="select_year"> 
       <option value={{form.year}}></option> 
       </select> 
     </div> 
    <button type="submit">Search</button> 
    </div> 
</form> 

模板2

<form id="search_dates" method="POST" action="/quantitative_analysis/"> 
    <div class="row"> 
     <div style="display:inline-block"> 
      <h6>Select year</h6> 
       <select name="select_year"> 
       <option value={{form.year}}></option> 
       </select> 
     </div> 
    <button type="submit">Search</button> 
    </div> 
</form> 

是改变是操作方法,所以我想知道是否有可能重新使用该变化仅在操作方法一个模板的唯一的事情。如果可能的话,你能帮我解码吗?

我检查了这个问题django - how to reuse a template for nearly identical models?但我没有在这里使用任何模型与我的模板。

+0

您可以从视图集本身发送操作属性,然后您可以重新使用模板 – Robert

回答

6

当然有一种方法。 {% include %}来拯救!

为表单创建一个基本模板,像这样:

<!-- form_template.html --> 

<form id="search_dates" method="POST" action="{{ action }}"> 
    <div class="row"> 
     <div style="display:inline-block"> 
      <h6>Select year</h6> 
       <select name="select_year"> 
       <option value={{form.year}}></option> 
       </select> 
     </div> 
    <button type="submit">Search</button> 
    </div> 
</form> 

注意占位符action。我们将在下一步中需要它。

现在,你可以重复使用这个模板,通过简单地写着:

<!-- a_template.html --> 

{% include 'form_template.html' with action='/tickets_per_day/' %} 


<!-- b_template.html --> 

{% include 'form_template.html' with action='/quantitative_analysis/' %} 
+0

只用于记录:使用'with action =/tickets_per_day /'其中'action = ...'不包含任何空格,否则您会遇到错误标签'Django不识别关键字参数' –

1
从你的观点

那么你可以在上下文传递action和使用,在模板这样你就不必创建两个单独的模板。比方说模板名称由两个视图abc.html

def my_view_a(request): 
    ctx = {'action': '/tickets_per_day/'} 
    return render(request, 'abc.html', ctx) 

def my_view_b(request): 
    ctx = {'action': '/quantitative_analysis/'} 
    return render(request, 'abc.html', ctx) 

然后在模板中,你会简单地做:

<form id="search_dates" method="POST" action="{{ action }}"> 

在上面的代码的作用是硬编码更好地使用reverse解决URL路径按名称:

ctx = {'action': reverse('namespace:url_name')} # replace namespace and url_name with actual values 
0

使用这template2

{% include "template1.html" with form=form %} 

它会工作。