簡體   English   中英

解決帶有pre標簽的HTML格式代碼的方法?

[英]Workaround for formatting code in HTML with pre tags?

我正在使用用於編寫HTML頁面的Python腳本。 它使用一系列開關來確定要寫入的頁面。 它還將<pre>標記用於代碼示例。 我不喜歡<pre>標記的地方是,它弄亂了.py腳本中的格式。 if / elif / else條件語句的層次結構被破壞了,因為現在標記保持對齊。 我知道<pre>標記會考慮空格,但是是否有必要在Python腳本中設置字段的格式,從而使代碼更清晰易懂且格式更好?

所以現在就這樣

def main():
    if true:
        page=<b>This is a sample</b>
<pre>
This is now left justified to match the pre tag but looks ugly in the code
</pre>
    else:
       page="<b>This would look much better</b>
       <pre>
            But all the white spacing to keep it aligned makes the HTML page 
            formatted wrong but it is much easier to read, edit here in the script
       </pre>
    return page

將字符串移到全局變量,甚至在單獨的模塊中:

sample_page = '''\
<b>This is a sample</b>
<pre>
This is now left justified to match the pre tag but looks ugly in the code
</pre>
'''

better_sample = '''\
<b>This would look much better</b>
<pre>
    But all the white spacing to keep it aligned makes the HTML page 
    formatted wrong but it is much easier to read, edit here in the script
</pre>
'''

注意這些是如何完全縮進的。

然后按常規流程使用它們:

if True:
    page = sample_page
else:
    page = better_sample

您可以輕松地將其與字符串格式結合使用; 字符串變量中的占位符,使用str.format()將其填充到常規流中。

更好的解決方案仍然是使用模板引擎來生成HTML輸出,例如ChameleonJinjaGenshi

它效率不高,但我會像這樣將字符串連接起來:

def main():
    if True:
        page = "<b>This is a sample</b>\n"
        page += "<pre>\nThis is now left justified...\n</pre>"
    else:
        page = "<b>...</b>"
        page += "..."

“ \\ n”字符將被解釋為換行符。 在這種情況下,第一個示例中的This將被證明是正確的。 只需根據需要添加空格。

如果您想使過程更有效率,可以使用StringIO ,如下所示:

import StringIO


def main():
    text = None
    if True:
        page = StringIO.StringIO()
        page.write("<b>Testing</b>\n")
        page.write("<pre>\nThis is left justified.\n</pre>")
    else:
        pass

    text = page.getvalue()
    page.close()
    return text


if __name__ == '__main__':
    print main()

注意#1 :標記外部不需要換行符,因為HTML不在乎空格。 如果您碰巧正在閱讀源代碼,則主要是為了提高可讀性。

注意#2 :我不會在任何生產環境中使用它,但是它可以用於簡單的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM