Tuesday, July 3, 2012

Re: Conditionals in Templates

Here's a workaround I came up with.

I defined a class:

class TableValue:
    def __init__(self, value):
        self.value = value
        self.is_list = isinstance(value, list)

Then in the Template I wrote

            <tbody>
            {% for row in rows %}
                <tr>
                    {% for cell in row %}
                        <td>
                                {% if cell.is_list %}
                                    <ul>
                                    {% for element in cell.value %}
                                        <li>{{ element }}</li>
                                    {% endfor %}
                                    </ul>
                                {% else %}
                                    {{ cell.value }}
                                {% endif %}
                        </td>
                    {% endfor %}
                </tr>
            {% endfor %}
            </tbody>

Is that considered decent Django?

On Tuesday, July 3, 2012 12:50:15 PM UTC-7, Russ Abbott wrote:
I'm generating a table. I want the cells to be different depending on the type of the content. How do I test for the type of the content? I'd like to do something like this.

            <tbody>
            {% for row in rows %}
                <tr>
                    {% for cell in row %}
                        <td>
                                {% if isinstance( {{ cell }}, list) %}
                                    <ul>
                                    {% for element in cell %}
                                        <li>{{  element  }}</li>
                                    {% endfor %}
                                    </ul>
                                {% else %}
                                    {{ cell }}
                                {% endif %}
                        </td>
                    {% endfor %}
                </tr>
            {% endfor %}
            </tbody>

But "{% if isinstance( {{ cell }}, list) %}" is not allowed. Apparently I can't call a function in an {% if ...  %} tag.  Is there another way to do this?

Thanks.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/HxfDQVmchj0J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment