【问题标题】:Generate HTML using Django-Polymorphic models使用 Django 多态模型生成 HTML
【发布时间】:2016-10-07 23:02:22
【问题描述】:

我可以根据 DJANGO-POLYMORPHIC 模型动态生成 HTML 吗?我想从表中读取所有行并根据类类型生成 div。还是这是不好的做法?

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

【问题讨论】:

    标签: python html django polymorphism django-polymorphic


    【解决方案1】:

    我不愿意这样编码。

    首先,您需要在上下文中传递 TextImage,而不管 you can't call a function in a template with parameters.

    我倾向于写一个模板标签或过滤器,或者更好,只是向类添加一个属性,返回它是“事物”的类型,您可以直接将其放入&lt;li&gt;&lt;/li&gt;

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

    还有……

    <ul>
    {% for c in content %}
            <li>c.description</li>
    {% endfor %}
    </ul>
    

    【讨论】:

    • 你对 if 'TextContent' in c.description elif 'ImageContent' in c.description 有什么看法?
    • 我有点想保持干燥,你的描述会被封装在课堂上的一个地方。然后你也可以在其他页面中使用它,并且不需要一遍又一遍地将类名翻译成一些很好的描述......description()甚至可以是每个子类的静态字符串,而不是self.__class__.__name__
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2023-03-12
    • 2013-03-26
    • 1970-01-01
    • 2019-01-04
    • 2014-04-05
    相关资源
    最近更新 更多