Jinja的多态宏

Dan*_*ner 2 python jinja2

我正在寻找一种方法来让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 %}
Run Code Online (Sandbox Code Playgroud)

在纯Python中,人们可以使用模块环境,例如globals()[x+'menuitem'],这不是很漂亮,但效果非常好.我尝试使用Jinja上下文类似的东西,但后者似乎不包含宏定义.

有什么更好的方法来实现我所寻求的目标?

fab*_*ioM 7

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"
Run Code Online (Sandbox Code Playgroud)

然后将只是一个问题:

{% macro menuitem(obj) %}
  {{ obj.present() }}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)