0

I am trying to populate a CSS grid in a Django template with specified columns and rows. To my best understanding, I need to do something like “nested variables” in the Django template to achieve what I’m looking for. I tried this, but it does not work:

   {% for parent_row in parent_rows %}
      {{ parent_row }}
      <div>p1</div>
      <div>p2</div>
      {% for child_row in children_rows %}
         <div> {{ child_row}} </div>
         {% for guy in guys %}
            <input type=”text” value=”{{guy}}.{{child_row}}”></input>
         {% endfor %}
      {% endfor %}
   {% endfor %}

The {{guy}}.{{child_row}} neither some of the similar variants I tried do not work. I manage to get the result I'm looking for by just writing the whole HTML open, and then by looping through each guy on separate rows, as I can use for example guy.name to get the desired value to each row, but this means lots of repetition.

parent_rows could look something like this for example:

“names”, “contact_information”, “hobbies”

children_rows could look something like this for example:

“forename”, “family_name”, “phone_number”, “mail”, “favourite_hobby”

and two records in the guys would be like this (both identical, to ease illustration):

“forename”: “Mike”
“family_name”: “McMediocre”
“phone_number”: “123”
“mail”: “[email protected]”
“favourite_hobby”: “tennis”

I am trying to populate the grid to look like this:

col1 col2 col3
names p1 p2
forename Mike Mike
family_name McMediocre McMediocre
contact_information p1 p2
phone_number 123 123
mail [email protected] [email protected]
hobbies p1 p2
favourite_hobby tennis tennis

EDIT: Found an answer ot my question from here. The accepted answer was useful in my situation as well.

0

1 Answer 1

0

Found an answer to my question from here.

The accepted answer (custom template filters) was useful in my situation as well. What I did was:

  1. Created a directory templatetags under MyApp

  2. Created a file named customtemplatetag.py to that directory

  3. Copy-pasted the snippet from the linked post:

    from django import template

    register = template.Library()

    @register.filter def get_obj_attr(obj, attr): return getattr(obj, attr)

  4. Added {% load mytemplatetag %} to my template

  5. Used {{guy|get_obj_attr:child_row}} in the template

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.