0

テンプレートには次のようなコードがたくさんあります。

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

上記のように、さらに多くのテーブルが作成されます。ご覧のとおり、重複したコードがたくさんあります。テーブルを作成するたびに多くのコードを繰り返さないように、これを行う方法はありますか? ありがとう。

アップデート

テーブルと呼ばれる新しいオブジェクトを作成し、結果とそれに対応する h2 タイトルを追加することを考えています。その後、テーブルと呼ばれるこれらのテーブル オブジェクトのリストを作成し、テンプレートに渡すことができます。その後、テンプレートはそれらを反復処理できます。

4

2 に答える 2

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から構築)についてのみ話すことができますが、メーカーのタイプごとに明示的な要求を使用して辞書を意図的に構築するか、「販売」のモデルと「メーカー」のモデルを用意することができます"そして、2つの間に多対多の関係を構築します。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

それは理にかなっていますか?

于 2011-01-29T10:30:03.030 に答える
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」という名前のファイルに入れて、テンプレートに含めます。フッターも同じ!

于 2011-01-29T10:27:01.800 に答える