django format_html flatatt 函数
admin
2023-08-01 18:00:07
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(’,’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))


相关内容

热门资讯

晋江鞋厂着火部位为1层,燃烧物... 7月9日12时4分许,位于福建泉州晋江市的辉腾鞋业有限公司发生火情,火灾发生时该厂房现场有237名本...
失守的坝,失联的人,失收的地 食通社说广西水灾救援还在继续中。在核心受灾区南宁横州,洪水横扫茉莉花、水稻、甘蔗、香蕉种植业及渔业、...
第一完成单位!隆平高科荣获20... 7月8日,2025年度国家科学技术奖励大会在北京隆重举行。由隆平高科作为第一完成单位,中信集团首席科...
2026智慧能源大会在成都开幕 成都7月9日电 (单鹏)由中国能源研究会等主办的2026智慧能源大会9日在成都开幕。本次活动汇聚来自...
国家科学技术“三大奖”揭晓,为... 7月8日,2025年度国家科学技术奖励大会在北京举行,国家自然科学奖、技术发明奖、科技进步奖“三大奖...
原创 安... 今天继续分享6月安卓性价比榜,这次的价格区间是4000元以上,性价比榜机型基于性能榜和京东自营价。比...
原创 向... 2026年的中国新能源汽车市场,仍在迅速“膨胀”。 一方面是市场体量的进一步扩张,乘联会公布的最新销...
每天捕蛇十七八个小时!广西横州... 近期,广西横州市因洪涝灾害导致一养蛇场被冲毁,多名村民被蛇咬伤,引发社会关注。“这两天干活太累,想休...
福建晋江鞋厂火灾现场疏散213... 记者采访了解到,福建晋江陈埭镇江头村的辉腾鞋业有限公司厂房火灾发生后,属地消防赶赴现场救援,调集救援...
“美伊战火重燃,所有人都在等穆... 美伊停火破局,战事是否会全面重启?伊朗社会又如何看待战火重燃?凤凰卫视驻伊朗记者李睿从德黑兰发回报道...