django format_html flatatt 函數

來源:互聯網
上載者:User

標籤:django format_html

最近項目需要,查看了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 函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.