V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2018-02-21 23:35:44 +08:00 · 1886 次点击
    这是一个创建于 2248 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

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

    想保留的话,有种做法就是用 html 解析库,有的解析库支持补全闭合标签。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5737 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 02:09 · PVG 10:09 · LAX 19:09 · JFK 22:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.