2011-01-29 50 views
0

我有很多這樣的代碼在我的模板:像上面那些創造Python:如何使用Jinja2以乾式方式實現這個?

<h2>Owners of old cars</h2> 
    <table id="hor-minimalist-b" summary="Old Cars"> 
    <thead> 
     <tr> 
      <th scope="col">Name</th> 
      <th scope="col">Age</th> 
      <th scope="col">Address</th> 
     </tr> 
    </thead> 
    <tbody> 
    {% for result in old_cars %} 
     <tr> 
      <td>{{result.name}}</td> 
      <td>{{result.age}}</td> 
      <td>{{result.address}}</td> 
     </tr> 
    {% endfor %} 
    </tbody> 
    </table>  

    <h2>Owners of Ford cars</h2> 
    <table id="hor-minimalist-b" summary="Old Cars"> 
    <thead> 
     <tr> 
      <th scope="col">Name</th> 
      <th scope="col">Age</th> 
      <th scope="col">Address</th> 
     </tr> 
    </thead> 
    <tbody> 
    {% for result in ford_cars %} 
     <tr> 
      <td>{{result.name}}</td> 
      <td>{{result.age}}</td> 
      <td>{{result.address}}</td> 
     </tr> 
    {% endfor %} 
    </tbody> 
    </table> 

將會有大量的多個表。正如你所看到的,有很多重複的代碼。無論如何要做到這一點,所以每次創建表格時我都不會重複太多的代碼?謝謝。

UPDATE

我正在考慮創建一個新的對象,稱爲表,並增加了結果和相應的H2所有權。然後我可以創建這些表格對象的列表,稱爲表格,我可以將它們傳遞給模板。然後模板可以遍歷它們。

回答

3

當然,你想要什麼,最好是:

{% for car in cars %} 
<h2>Owners of {{ car.manufacturer }}</h2> 
<table id="hor-minimalist-b" summary="Old Cars"> 
<thead> 
    <tr> 
     <th scope="col">Name</th> 
     <th scope="col">Age</th> 
     <th scope="col">Address</th> 
    </tr> 
</thead> 
<tbody> 
    {% for model in car.models %} 
    <tr> 
     <td>{{model.name}}</td> 
     <td>{{model.age}}</td> 
     <td>{{model.address}}</td> 
    </tr> 
    {% endfor %} 
</tbody> 
</table> 
{% endfor %} 

我不知道什麼ORM你使用,但在Django,不會太硬,構建;畢竟,你傳入的是一個包含子對象和字段的對象列表。

同樣,我只能說一個django視角(從你自己的ORM構造而來),但是你可以有意識地爲每種類型的製造商建立明確的請求字典,或者有一個「銷售」模型和一個爲「製造商」建立模型,並在兩者之間建立多對多的關係。你的查詢大致看起來像這樣,在Django的蟒蛇:

result = [] 
manufacturers = Manufacturer.objects.all() # get all manuf 
for m in manufacturer: 
    mf = dict() 
    mf["manufacturer"] = m.name 
    mf["models"] = m.model_set.all() # get all linked models 
    result.append(mf) 
# pass result to template as cars 

這是否有道理?

+0

是的。謝謝。 – Ambrosio 2011-01-29 10:37:22

0

爲表

<table id="hor-minimalist-b" summary="Old Cars"> 
<thead> 
    <tr> 
     <th scope="col">Name</th> 
     <th scope="col">Age</th> 
     <th scope="col">Address</th> 
    </tr> 
</thead> 
<tbody> 

的頁眉和頁腳使用模板把這個名爲「table_header.html」文件,並將其包含在您的模板。 頁腳也一樣!

相關問題