0

Can I generate HTML dynamically based on DJANGO-POLYMORPHIC Models? I'd like to read all of the rows from a table and generate divs based on the class type. Or is this bad practice?

{% if content %}
{% for c in content %}
<ul>
    {%  if c.instance_of(Text) %}
        <li>TEXT</li>
    {% endif %}
    {%  if c.instance_of(Image) %}
        <li>IMAGE</li>
    {% endif %}
</ul>
{% endfor %}
{% else %}
<p>No content available.</p>
{% endif %}
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65

1 Answers1

1

I'd be reluctant to code it like that.

First, you'll need to pass Text and Image in your context, and regardless you can't call a function in a template with parameters.

I'd be inclined to either write a template tag or filter, or better, just add a property to the class that returns the type of "thing" it is, which you could put directly into the <li></li>

class Foo(PolymorphicModel):
    def description(self):
        return self.__class__.__name__

And...

<ul>
{% for c in content %}
        <li>c.description</li>
{% endfor %}
</ul>
Community
  • 1
  • 1
rrauenza
  • 6,285
  • 4
  • 32
  • 57
  • Whats your thoughts on if 'TextContent' in c.description elif 'ImageContent' in c.description? – Alan Kavanagh Jun 07 '16 at 21:56
  • I kinda feel like to keep it DRY, your description would be encapsulated in one place in the class. Then you could use it in other pages as well and wouldn't need to translate the class name into some nice description over and over ... `description()` could even be a static string per subclass, not `self.__class__.__name__` – rrauenza Jun 07 '16 at 21:58