【问题标题】:Django template iteration through structureDjango模板迭代通过结构
【发布时间】:2017-10-31 11:46:58
【问题描述】:

早上好 我有来自后端的以下结构:

sentences_info = [
    {
        "keyword": "",
        "sentences": [
            {
                "sentence_id": "",
                "sentence": ""
            },
            ...
        ],
        ...
    },
    ...
]

我需要将此结构以复选框形式放入我的模板中,如下所示:

<form>
    <h3>Keyword: {{ keyword }}</h3>
    <div class="form-check">
        <label class="form-check-label">
            <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}">
            {{ sentence }}
        </label>
        <label class="form-check-label">
            <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}">
            {{ sentence }}
        </label>
        ...
    </div>
    <h3>Keyword: {{ keyword }}</h3>
    <div class="form-check">
        <label class="form-check-label">
            <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}">
            {{ sentence }}
        </label>
        <label class="form-check-label">
            <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}">
            {{ sentence }}
        </label>
        ...
    </div>
    ...
</form>

我尝试了一些迭代,但到目前为止将它放在模板上没有意义..有人可以帮助我吗?

【问题讨论】:

    标签: python html django templates


    【解决方案1】:

    你试过吗? 前提是sentence_info 在上下文中。

    <form>
    {% for info in sentences_info %}
    <h3>Keyword: {{ info.keyword }}</h3>
    <div class="form-check">
    {% for sentence in info.sentences %}
        <label class="form-check-label">
            <input type="checkbox" class="form-check-input" id="{{ sentence.sentence_id }}" value="{{ sentence.sentence_id }}">
            {{ sentence.sentence }}
        </label>
    {% endfor %}
    </div>
    {% endfor %}
    </form>
    

    【讨论】:

      【解决方案2】:

      你应该可以的;

      {% for sentence in sentence_info %}
          <h3>Keyword: {{ sentence.keyword }}</h3>
          {% for s in sentence.sentences %}
              <div class="form-check">
                  <label class="form-check-label">
                      <input type="checkbox" class="form-check-input" id="{{ s.sentence_id }}" value="{{ s.sentence_id }}">
                  {{ s.sentence }}
              </label>
          {% endfor %}
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-01
        • 1970-01-01
        • 2021-06-17
        • 2015-12-10
        • 2012-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多