【问题标题】:How to make html markup show up? [duplicate]如何使 html 标记显示出来? [复制]
【发布时间】:2019-06-20 20:19:36
【问题描述】:

所以我是 HTML 新手。我正在用烧瓶构建一个网络应用程序。我正在尝试可视化一些 HTML 标记,但它没有正确显示。

我有以下烧瓶路线:

@app.route('/predict',methods=['GET','POST'])
def api():
    if request.method == "POST":

        input_data = request.form['rawtext']
        output_data = model_api(input_data)
        alignedText = output_data["words"]
        predictions = output_data["predictions"]
        #response = jsonify(output_data)
        print(predictions, flush=True)

        if request.values.get('type') == 'image':
            text = output_data["text"]
            ents = turnIntoSpacyFormat((predictions))
            inp = {"text": text, "ents": ents, "title": None}
            htmlm = displacy.render(inp, style="ent", manual=True)

            return render_template('index.html', text=alignedText, predictions=predictions, htmlm=htmlm)
        else:
            return render_template('index.html', text=alignedText, predictions=predictions)
    else:
        return render_template('index.html')

函数 displacy.render 返回 html 标记。我将它传递给 index.html。我尝试打印的部分如下(最后几行):

      <!-- Result Display-->
  <section class="section section-solutions-about grey darken-2">
 <div class="container white-text">

      <!--   Icon Section   -->
      <div class="row">
        <div class="col s12 m6">
          <div class="icon-block">

            <!--<h5 class="center">Your Text</h5>-->
             <p>Text:&nbsp;&nbsp;&nbsp;&nbsp; <span style="color:#0091EA;">{{ text }} </span></p>
            <!--<p class="light">{{ctext}}</p>-->
            <div class="alert alert-info" role="alert"><p>Entities: <span style="color:#0091EA;">{{ predictions }} </span></p><br/>
            </div>

          </div>
        </div>

      </div>
     <div class="entities" style="line-height: 2.5; direction: ltr"> Doesn't show up correctly</div>
     {{ htmlm }}

  </div>
</section>

我在想我可以让它显示在 html 页面上:{{ htmlm }}

显然,它会打印标记的字符串表示形式。首先,我认为标记可能有问题。但是,当我在 html 文件中输入完全相同的内容时,例如 {{ htmlm }} 命令上方的一行,它会根据需要显示。

这是打印的内容: 第一行是所需的,通过将 html 标记粘贴到 html 文件中来显示。第二个输出是我通过访问 htmlm 变量得到的结果。

有人知道怎么做吗?

【问题讨论】:

  • 我很好奇如果你使用{{ htmlm|safe }}会发生什么
  • 谢谢老兄,成功了!你能告诉我它是做什么的吗?谷歌搜索没有给我任何结果。
  • 好吧,没关系,刚刚找到了。

标签: python html flask


【解决方案1】:

生成的 HTML 正在被转义;您需要将其标记为{{ htmlm|safe }}

根据Jinja docs

...默认配置是不自动转义;对于各种 原因:

  • 转义除安全值之外的所有内容也意味着 Jinja 正在转义已知不包含 HTML 的变量(例如数字、 布尔值),这可能会对性能造成巨大影响。
  • 有关变量安全性的信息非常脆弱。通过强制安全和不安全值,返回值可能会发生 是双转义的 HTML。

然而in Flask,自动转义在很多情况下被设置为默认值:

除非自定义,Jinja2 由 Flask 配置如下:

  • 使用 render_template() 时,所有以 .html、.htm、.xml 和 .xhtml 结尾的模板都启用了自动转义。
  • 使用 render_template_string() 时,所有字符串都启用了自动转义。模板可以选择加入/退出 使用 {% autoescape %} 标签自动转义。
  • Flask 将几个全局函数和助手插入到 Jinja2 上下文中,此外还有由 默认。

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2010-11-30
    • 2015-08-06
    • 2017-08-26
    • 2016-04-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多