pythonfiltercheetah

Cheetah template filters


Sorry if the question sounds naive. I have a cheetah template, e.g:

#filter None
<html>
<body>
$none should be ''
$number should be '1'
</body>
</html>
#end filter

with namespace = {'none': None, 'number': 1}
So basically I want to convert all None and non-string values to '' and string respectively. According to Cheetah's doc: http://www.cheetahtemplate.org/docs/users_guide_html_multipage/output.filter.html , what I want is the default filter. Isn't that what I did by putting #filter None at the beginning? How come it doesn't work?

Please help me get this right. Thanks

EDIT:
To make it clearer, basically I want it to pass this simple if test:

#filter None
<html>
<body>
#if $none == '' and $number == '1':
<b>yay</b>
#end if
</body>
</html>
#end filter

So if it works out all i should see is yay


Solution

  • To explain the results you're getting, let's define this:

    def filter_to_string(value):
        if value is None:
            return ''
        return str(value)
    

    Let's imagine that's our filter. Now, let's be naïve about how Cheetah does the processing (it's a bit more involved than this). The result you're getting would come from this:

    >>> "<html>\n<body>\n" + \
        filter_to_string(ns['none']) + " should be ''\n" + \
        filter_to_string(ns['number']) + " should be '1'\n</body>\n</html>\n"
    "<html>\n<body>\n should be ''\n1 should be '1'\n</body>\n</html>\n"
    

    where ns would be the namespace.

    Given that, does your result still surprises you?