推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
miniyao
V2EX  ›  Python

用模板 truncate()截断 html 内容之后,怎么保证 html 标签闭合呢?

  •  
  •   miniyao · Feb 21, 2018 · 2588 views
    This topic created in 3172 days ago, the information mentioned may be changed or developed.

    用 jinja2 模板,{{ content.html | safe | truncate(500) }} 截断 html 内容之后,有时候刚巧会截到 500 个字符的地方是 html 标签的闭合位置,造成一半标签留在页面上,另外一半被截掉了,例如这样:

    text text text text text <code>print('hello world ...

    剩下的 ')</code> 就被截掉了。最糟糕的是,如果这个 truncate()是在一个 loop 里,浏览器 Chrome/Firefox 都会自作聪明的在后面自动补全来关闭标签。结果整个页面就全乱掉了

    2 replies  •  2018-02-22 08:52:44 +08:00
    ipwx
        1
    ipwx  
       Feb 22, 2018   ❤️ 1
    cxh116
        2
    cxh116  
       Feb 22, 2018 via Android   ❤️ 1
    最简单的做法就是删除所有标签再截取。

    想保留的话,有种做法就是用 html 解析库,有的解析库支持补全闭合标签。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4046 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 04:10 · PVG 12:10 · LAX 21:10 · JFK 00:10
    ♥ Do have faith in what you're doing.