繁体   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