tornado template后html自动缩进问题的解决

因为之前博客园不怎么用,所以随便往上记录了很多很没必要的东西,而我也看不惯这些记录很久了,很早就打算遇到更合适记录的问题,就把之前的覆盖掉,正好这次开发任务遇到一个很奇怪的问题,花了不小功夫才找到解决方案,所以就从第一篇起开始覆盖了~

问题起源:当使用tornado时渲染时,如果按照网上大部分教程来操作,会遇到一个很奇怪的问题,tornado会自动把html页面的缩进全部取消,这就有问题了,美观是其次,主要公司提出必须保留原格式,所以就开始了google之旅。。

最后在https://github.com/tornadoweb/tornado/issues/178找到了解决方案,最下面tornado大佬Ben Darnell提出一种解决方案

I've introduced several new ways to control whitespace handling: the template_whitespace Application setting, the whitespace argument to the template Loader constructor, and the {% whitespace *mode* %} directive inside a template itself.

Available modes are single (collapse repeated whitespace to a single character, while preserving newlines. This is currently the default for files named .html or .js), all (preserve all whitespace as found in the template source, currently the default for all other files), and oneline (like single but replace newlines with spaces instead of preserving them).

In addition, the {% include %} directive no longer causes the included template to inherit its parent's whitespace mode.

将whitespace—compress关闭的方案其中之一是the template_whitespace Application setting

# 定义服务器
def main():
    # 解析命令行参数
    tornado.options.parse_command_line()
    # 创建应用实例
    app = tornado.web.Application(urls, static_path=static_dir, template_path=template_dir, template_whitespace="all")
    # 监听端口
    app.listen(options.port)
    # 创建IOLoop实例并启动
    tornado.ioloop.IOLoop.current().start()

如上所示,将Application中加入template_whitespace参数,具体起效函数如下,有all、single、online三个选项

def filter_whitespace(mode: str, text: str) -> str:
    """Transform whitespace in ``text`` according to ``mode``.

    Available modes are:

    * ``all``: Return all whitespace unmodified.
    * ``single``: Collapse consecutive whitespace with a single whitespace
      character, preserving newlines.
    * ``oneline``: Collapse all runs of whitespace into a single space
      character, removing all newlines in the process.

    .. versionadded:: 4.3
    """
    if mode == "all":
        return text
    elif mode == "single":
        text = re.sub(r"([	 ]+)", " ", text)
        text = re.sub(r"(s*
s*)", "
", text)
        return text
    elif mode == "oneline":
        return re.sub(r"(s+)", " ", text)
    else:
        raise Exception("invalid whitespace mode %s" % mode)

其实不是什么大问题,就是配置。记录下来是因为比较难找,且好像网上目前还没有人提出这个问题很好的解决方案(至少我是没查到..),所以谨此记录一下。

后续:以上问题基本就没有了,改完之后tornado随之而来的一个问题是,template_whitespace设置all的话,就不再进行CRLF与LF之间的转换,所以html文件是什么格式,就会渲染返回什么格式。这个要说不是什么大问题,也是和我们目前业务有一定冲突,一般情况应该不需要关注。

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 有任何问题请随时交流~ Email: araise1@163.com
原文地址:https://www.cnblogs.com/seasen/p/10231628.html