Search code examples
pythontemplatescheetah

Check if Cheetah Template Dict has key


I am trying to come up with a base template for an application and one of the goals would be to remove any unnecessary js/css from pages so I want to do something in the cheetah template like

#if $dict.has_key('datepicker'):
  <link rel="stylesheet" href="$datepicker" type="text/css" />
#end if

I think this would also help with errors like namemap does not have key 'datepicker'

my current error I am getting using WSGIHandler is

TypeError: descriptor 'has_key' requires a 'dict' object but received a 'str'

I feel like this has to do with me casting the return of the handler as a str but shouldnt the template be parsed before it gets to the str

t = Template(file=WORKSPACE_PATH+"/tmpl/posts.html", searchList=[tmpldict])
self.response_body = str(t).encode('utf8')
return str(t)

Solution

  • The bug is this:

    dict.has_key('datepicker')
    

    "dict" is a class, so it expects the first argument of "dict.has_key" to be an instance of "dict".

    You're passing a string instead of the dict object.

    Basically, "d.has_key(k)" is equivalent to "dict.has_key(d, k)", and you have the latter.