問題描述
在 python 中,最優雅的方法是生成 HTML 檔案。我目前手動將所有標籤附加到一個巨大的字串,並將其寫入一個檔案。有更優雅的做法嗎?
最佳解決辦法
我建議使用可用於 python 的許多模板語言之一,例如一個 built into Django(您不必使用其餘的 Django 來使用其模板引擎) – 一個谷歌查詢應該給你很多其他替代模板實現。
我發現,學習模板庫有很多方面的幫助 – 無論何時需要生成 e-mail,HTML 頁面,文字檔案或類似檔案,您只需編寫一個模板,將其載入到模板庫中,然後讓模板程式碼建立完成產品。
這裡有一些簡單的程式碼讓你開始:
#!/usr/bin/env python
from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""
t = Template(template)
c = Context({"title": "title from code",
"mystring":"string from code"})
print t.render(c)
如果您在磁碟上有模板,請檢視 render_to_string 函式,從而可以從預定義的搜尋路徑列表中載入模板,並從字串中填充資料並將其渲染為字串,這一切都在一個函式呼叫中。
次佳解決辦法
我發現 yattag 是最優雅的做法。
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('body'):
with tag('p', id = 'main'):
text('some text')
with tag('a', href='/my-url'):
text('some link')
result = doc.getvalue()
它看起來像 html,附加的好處,你不必關閉標籤。
第三種解決辦法
我建議使用 xml.dom 來做到這一點。
http://docs.python.org/library/xml.dom.html
閱讀本手冊頁,它具有構建 XML(因此 XHTML) 的方法。它使所有 XML 任務更容易,包括新增子節點,檔案型別,新增屬性,建立文位元組點。這應該能夠幫助您絕大多數您將要建立的 HTML 。
它也對分析和處理現有的 xml 檔案非常有用。
希望這可以幫助
P.S
這是一個教程,可以幫助您應用語法
http://www.postneo.com/projects/pyxml/
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。