开发者

Mako template depending on object class?

开发者 https://www.devze.com 2022-12-28 05:33 出处:网络
whats a clean开发者_Go百科 way to use different templates depending on an object class?other than buncha if statementsYou can make a dict, call it type2templ, with types (i.e., classes) as the keys, a

whats a clean开发者_Go百科 way to use different templates depending on an object class? other than buncha if statements


You can make a dict, call it type2templ, with types (i.e., classes) as the keys, and mako.template.Template instances as the values -- then

t = type2templ.get(type(theobj), default_templ)
... t.render() ...

This assumes that theobj is an instance of a new-style class (not the obsolete, best-avoided "legacy" classes that are still the default in Python 2 -- if you use those, you should definitely upgrade your code to new-style classes, but using theobj.__class__ is a workable, if hackish, replacement for type(theobj) here). default_templ is a default template instance to use for "none of the above" (if you'd rather have an exception when theobj is of a non-recognized type, use square-bracket indexing instead of the .get call).

Note that this doesn't (directly) "support inheritance" -- if (for example) class foo maps in type2templ to template bar, then you make a subclass baz of foo but don't explicitly record in type2templ what template its instances should use, you'll get the default template for baz's instances. Supporting inheritance is more complex -- unless you just make the mako template instance one of the class attributes, of course, which makes it trivial (just theobj.thetempl if you name that attribute thetempl!-), but I do understand to separate the view from the model.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号