python的Template


Template模塊,可以用來制作web頁面的模板,非常的方便。

 

Template屬於string中的一個類,所以要使用的話要在頭部引入:

1 from string import Template

模板替換變量采用的是$符號,而不是%,它的使用要遵循以下規則:

  • $$ 是需要規避,已經采用一個單獨的 $代替($$相當於輸出$,而不是變量)
  • $identifier 變量由一個占位符替換(key),key去匹配變量 "identifier" 
  • ${identifier}相當於 $identifier. 它被用於當占位符后直接跟隨一個不屬於占位符的字符,列如 "${noun}ification"

Template中有兩個重要的方法:substitute和safe_substitute,如下標紅的方法名

 1 class string.Template(template)
 2 The constructor takes a single argument which is the template string.
 3 
 4 substitute(mapping, **kwds)
 5 Performs the template substitution, returning a new string. mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, you can provide keyword arguments, where the keywords are the placeholders. When both mapping and kwds are given and there are duplicates, the placeholders from kwds take precedence.
 6 
 7 safe_substitute(mapping, **kwds)
 8 Like substitute(), except that if placeholders are missing from mapping and kwds, instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact. Also, unlike with substitute(), any other appearances of the $ will simply return $ instead of raising ValueError.
 9 
10 While other exceptions may still occur, this method is called “safe” because substitutions always tries to return a usable string instead of raising an exception. In another sense, safe_substitute() may be anything other than safe, since it will silently ignore malformed templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers.

 測試代碼--規則:

1 s1 = Template('$who likes $what')
2 print(s1.substitute(who='tim', what='kung pao'))
3 
4 s2 = Template('${who}likes $what')
5 print(s2.substitute(who='tim', what='kung pao'))
6 
7 s3 = Template('$$who likes $what')
8 print(s3.substitute(who='tim', what='kung pao'))

輸出:

tim likes kung pao
timlikes kung pao
$who likes kung pao

測試代碼--safe_substitute和substitute區別:

1 d = dict(who='java')
2 print(Template('$who need $100').safe_substitute(d))
3 print(Template('$who need $100').substitute(d))

輸出:

java need $100
Traceback (most recent call last):

使用safe_substitute可以正常輸出,而使用substitute會出錯,需要把$100改成$$100

substitute比較嚴格,必須每一個占位符都找到對應的變量,不然就會報錯,而safe_substitute則會把未找到的$XXX直接輸出

參考資料:https://docs.python.org/3.4/library/string.html#template-strings

  https://my.oschina.net/u/241670/blog/309856

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM