alvarosps
alvarosps

Reputation: 83

Django template iteration through structure

Good morning I have the following structure coming from the backend:

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

I need to put this structure in my template, in a checkbox form, like this:

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

I tried some iterations, but can't make sense to put this on the template so far..can someone help me, please?

Upvotes: 0

Views: 33

Answers (2)

markwalker_
markwalker_

Reputation: 12849

You should be able to do;

{% 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 %}

Upvotes: 1

durdenk
durdenk

Reputation: 1660

Have you tried this? Provided that sentences_info is in context.

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

Upvotes: 1

Related Questions