如何避免在mako的%def中重复使用过滤器规范?

13

我发现自己在mako代码中的所有%def中都要重复相同的过滤器属性:

<%def name="mydef1(a,b)" filter="trim">
# something something something
</%def>

... 

<%def name="mydef2(b)" filter="trim">
# something something something
</%def>

有没有一种方法可以为所有的%def指定默认的过滤器,避免在我的代码中重复写"filter =“trim”"?

我注意到有一种选项可以指定表达式过滤器的默认过滤器, 但我找不到类似于%def的东西。


1
有一个名为buffer_filters的选项,它能够为%def指定默认过滤器。但是它仅适用于使用buffered="True"定义的%def。我认为最好的解决方案是在Mako的存储库中提出问题,并要求添加此功能。或者您始终可以猴子补丁DefTag类以将过滤器添加到每个%def >.< - Yaroslav Admin
1个回答

2

您可以使用几种解决方法:

  1. You can use the default_filters argument if you are okay importing the defs programmatically or by loading them from a file.
  2. You can nest the defs within a parent def, and apply the filtering to the parent def (I don't have mako on my current machine, so I can't text this, but I am 99% sure this works, please call me out if I am wrong.)

    <%def name="filterdefs()" filter="trim">
    
        <%def name="mydef1(a,b)">
        # something something something
        </%def>
    
        <%def name="mydef2(b)">
        # something something something
        </%def>
    
    </def>
    
  3. Finally, you could use buffer_filters as suggested in the comments. However, instead of adding buffered="True" you can just call the def with capture(myDef) instead of myDef()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接