2011-01-29 4 views
0

은 내 템플릿에 같은 코드를 많이 가지고 : 위의 사람들처럼 만들어Python : Jinja2를 사용하여 DRY 방식으로 어떻게 구현할 수 있습니까?

<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 타이틀을 추가하는 방법에 대해 생각하고 있어요. 그런 다음 템플릿이라는 테이블에 전달할 수있는 테이블 개체의 목록을 만들 수 있습니다. 그런 다음 템플릿을 반복 할 수 있습니다. 테이블

<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> 

의 머리글과 바닥 글에 대한

답변

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하지만, 장고에 구축 너무 어렵지 않을 것이라고 모르겠어요; 결국 당신이 전달하는 것은 하위 객체와 필드가있는 객체의 목록입니다.

다시 말하지만, 장고 관점 (자신의 ORM으로 구성)에 대해서만 이야기 할 수 있지만 각 제조업체 유형에 대한 명시 적 요청을 사용하여 의도적으로 사전을 구성하거나 "판매"및 "제조업체"에 대한 모델을 작성하고이 둘 사이에 다 대다 관계를 구성하십시오. 귀하의 질의는 django python에서 대략 다음과 같습니다 :

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

0

사용 템플릿은 "table_header.html"라는 이름의 파일이 넣고 템플릿에 포함. 바닥 글과 동일합니다!

관련 문제