温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django format_html flatatt 函数

发布时间:2020-08-04 14:51:56 来源:网络 阅读:2501 作者:weidabao123 栏目:开发技术

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))


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI