首页 > Web开发 > 详细

django format_html flatatt 函数

时间:2017-01-03 17:28:48      阅读:276      评论:0      收藏:0      [点我收藏+]

最近项目需要,查看了django源码,其中比较常用的函数format_html,用于生成html模板

def format_html(format_string, *args, **kwargs):
    """
    Similar to str.format, but passes allarguments through conditional_escape,
    and calls ‘mark_safe‘ on the result. Thisfunction should be used instead
    of str.format or % interpolation to buildup small HTML fragments.
    """
    args_safe = map(conditional_escape, args)
    kwargs_safe = {k: conditional_escape(v) for(k, v) in six.iteritems(kwargs)}
return mark_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’

def flatatt(attrs):
  """
  Convert adictionary of attributes toa single string.
  The returnedstring will contain aleading space followed by key="value",
  XML-stylepairs.It is assumed that the keys do not need to beXML-escaped.
  If thepassed dictionary is empty,then return an empty string.    
  The resultis passed through‘mark_safe‘.
  """    
  key_value_attrs = []   
  boolean_attrs = []    
  for attr,value in attrs.items():        
    if isinstance(value, bool):            
      if value:               
         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))


本文出自 “Paniho” 博客,请务必保留此出处http://3379770.blog.51cto.com/3369770/1888537

django format_html flatatt 函数

原文:http://3379770.blog.51cto.com/3369770/1888537

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!