Django中的常用的函数format_html,用于格式化生成html模板

defformat_html(format_string,*args,**kwargs):"""Similartostr.format,butpassesallargumentsthroughconditional_escape,andcalls'mark_safe'ontheresult.Thisfunctionshouldbeusedinsteadofstr.formator%interpolationtobuildupsmallHTMLfragments."""args_safe=map(conditional_escape,args)kwargs_safe={k:conditional_escape(v)for(k,v)insix.iteritems(kwargs)}returnmark_safe(format_string.format(*args_safe,**kwargs_safe))

可以看到文档说明,format_html类似于str.format函数,格式化生成html元素。

select_html=format_html(‘<select{}>’,’id=id_birth’)


另外一个函数flatatt函数,将字典转换为单个字符串 key=”value”的形式,,如 {‘height’:30,’width’:20,’required’:True},将会转换为字符串‘height=20 widt=30 requried’

defflatatt(attrs):"""Convertadictionaryofattributestoasinglestring.Thereturnedstringwillcontainaleadingspacefollowedbykey="value",XML-stylepairs.ItisassumedthatthekeysdonotneedtobeXML-escaped.Ifthepasseddictionaryisempty,thenreturnanemptystring.Theresultispassedthrough'mark_safe'."""key_value_attrs=[]boolean_attrs=[]forattr,valueinattrs.items():ifisinstance(value,bool):ifvalue:boolean_attrs.append((attr,))else:key_value_attrs.append((attr,value))return(format_html_join('','{}="{}"',sorted(key_value_attrs))+format_html_join('','{}',sorted(boolean_attrs))