【问题标题】:Strip unwanted html entieties去除不需要的 html 实体
【发布时间】:2022-01-11 07:55:40
【问题描述】:

我正在将 mezzanine/django 应用程序从 Mezzanine4.x/python2.7 升级到 Mezzanine5.0/python3.7。我的 HTML 页面是使用模板标签创建的。现在,当使用浏览器(Firefox 或 Chrome)view page source 功能检查时,升级后的页面会显示不需要的 html 实体。在 python 2.7 中它看起来像

 <p><a href='/'>Etusivu</a> > Ajankohtaista</p> 

而在 python 3.7 中显示

  <p>&lt;a href=&#39;/&#39;&gt;Etusivu tags1&lt;/a&gt; &gt; Ajankohtaista</p>

浏览器的inspect element 功能看不到这些不需要的实体。

来自 html:

<!doctype html>

{% load pages_tags mezzanine_tags i18n future staticfiles statfi_tags %}

<body id="{% block body_id %}body{% endblock %}">

{% block base %}
    <div id="container">
        <main id="page">
            <div class="row">
                <div id="breadcrumbs" class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
                    {% block breadcrumbs %}
                        {% if page.basicpage %}
                            <p>{% anna_murut page.basicpage %}</p>
                        {% endif %}
                    {% endblock %}
                </div>                                                                                                
            </div>
            {% endblock %}
        </main>  
    </div>    
{% endblock %}

</body>
</html>

来自 statfi_tags.py

# -*- coding: utf-8 -*-

from django import template
from datetime import date
from page_types import models
from django.db import models
from django.contrib.sites.models import Site
from django.template import Context, RequestContext
from django.template import Library, Node
from page_types.models import BasicPage, RegisterDescPage
from mezzanine.pages.models import Page, Link
from django.utils.encoding import *

register = template.Library()

def anna_murut(BasicPage):
  sivu = BasicPage
  letka = letka = u"<a href='/'>Etusivu</a> > "     
    if not "/" + BasicPage.slug == site_url(BasicPage):
      letka += u"<a href='"+ site_url(BasicPage) +"'>"+ str(paasite(BasicPage)) +"</a> > " 
    letka += BasicPage.title
  return letka

register.simple_tag(anna_murut)

浏览器中的 Python 2.7 版本:

浏览器中的 Python 3.7 版本:

任何想法如何修复 python 3.7 版本?我不知道它可以在 python 代码中修复,因为当我打印函数“anna_murut”返回的字符串时会看到不需要的实体。

【问题讨论】:

    标签: python html jinja2 templatetags


    【解决方案1】:

    较新的 Django 版本默认将简单标签标记为不安全,这意味着它们可能包含用户提交的有害代码,因此 Django 将转义任何“危险”的 HTML 标签。

    您必须将自定义标签返回的任何字符串mark explicitly 视为安全,以避免默认转义。

    from django.utils.safestring import mark_safe
    
    def anna_murut(BasicPage):
        # ...
        return mark_safe(letka)
    

    只需确保letka 不包含任何未转义的用户提交的内容。

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多