我正在寻找一种方法来让 Jinja 宏根据传递的对象类型调用不同的实现。基本上,标准的 Python 方法多态性。现在,我正在使用与此类似的丑陋解决方法:
{% macro menuitem(obj) %}
{% set type = obj.__class__.__name__ %}
{% if type == "ImageMenuItem" %}
{{ imagemenuitem(obj) }}
{% elif type == "FoobarMenuItem" %}
{{ foobarmenuitem(obj) }}
{% else %}
{{ textmenuitem(obj) }}
{% endif %}
{% endmacro %}
在纯 Python 中,可以随意使用模块环境,例如globals()[x+'menuitem']
,虽然不漂亮,但效果很好。我使用 Jinja 上下文尝试过类似的东西,但后者似乎不包含宏定义。
有什么更好的方法可以实现我的目标?
最佳答案
OOP的本质:多态。
Create a presentation Layer for your objects:
class MenuPresentation:
def present(self):
raise NotImplementedException()
class ImageMenuPresentation(MenuPresentation):
def present(self):
return "magic url "
class TextMenuPresentation(MenuPresentation):
def present(self):
return "- text value here"
然后就是:
{% macro menuitem(obj) %}
{{ obj.present() }}
{% endmacro %}
关于python - Jinja 中的多态宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6428484/