13

I find myself repeating the same filter attribute over all the %def's in my mako code:

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

... 

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

Is there a way to specify a default set of filters for all %def's and avoid the repetitive 'filter="trim"' in my code?

I noticed there is an option to specify default filters for expression filters, but i could not find something similar for %def's.

zr.
  • 7,528
  • 11
  • 50
  • 84
  • 1
    There is option called [`buffer_filters`](http://docs.makotemplates.org/en/latest/usage.html#mako.template.Template.params.buffer_filters), which is able to specify default filters for the `%def`'s. However it works only for `%def`'s defined with `buffered="True"`. I think the best solution is to raise issue in the [Mako's repository](https://bitbucket.org/zzzeek/mako/issues) and ask for adding this functionality. Or you always can monkey patch the `DefTag` class to add filter to every `%def` >. – Yaroslav Admin Jul 24 '15 at 22:50

1 Answers1

2

There are a couple workarounds you can use:

  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()

Parker
  • 8,539
  • 10
  • 69
  • 98