溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

django format_html flatatt 函數(shù)

發(fā)布時(shí)間:2020-08-04 14:51:56 來源:網(wǎng)絡(luò) 閱讀:2502 作者:weidabao123 欄目:開發(fā)技術(shù)

Django中的常用的函數(shù)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函數(shù),格式化生成html元素。

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


另外一個(gè)函數(shù)flatatt函數(shù),將字典轉(zhuǎn)換為單個(gè)字符串 key=”value”的形式,,如 {‘height’:30,’width’:20,’required’:True},將會(huì)轉(zhuǎn)換為字符串‘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問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI