如何将格式化的句子数组传递到Flask模板?

2024-04-26 11:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何将一组html格式的句子传递到flask模板。在

@app.route('/', methods=['POST'])
def my_form_post():
    question = request.form['question'].lower()
    text = request.form['text'].lower()

    open = '<div class="tooltip">'
    after_sentence = '<span class="tooltiptext">'
    close = '</span> </div>'

    out = text + " <mark> " +  question + " </mark>"

    return render_template('layout.html', text_out = tooltip, text_out2 = tooltip2)

在模板中我有

^{pr2}$

这很管用。但我想格式化文本中的每一个句子(我不能硬编码)(例如,为每个句子提供工具提示,并将其作为数组传递到同一个div中的同一个模板。我该怎么做呢?在

这样的Smth会产生模板错误

open = '<div class="tooltip">'
after_sentence = '<span class="tooltiptext">'
close = '</span> </div>'

tooltip = "first"
tooltip2 = "second"
first = open + "hello" + after_sentence + tooltip + close
second = open + "hello2" + after_sentence + tooltip2 + close
list = [first, second]
return render_template('layout.html', list)

以及

  <div id="_out">

  <!-- {{text_out|safe}}

  {{text_out2|safe}} -->

  {% for item in {{list}} %}
  item 
  {% endfor %}

 </div>

把列表转换成字典也没用

list={“first”:第一,“second”:second} return render_template('布局.html',列表)

给了我

TypeError: render_template() takes 1 positional argument but 2 were given

谢谢

已解决: 你需要把字典递给我

render_template("layout.html", dic=dic)

不是

render_template("layout.html", dic)

Tags: textdiv模板closehtmltemplateopenrender
1条回答
网友
1楼 · 发布于 2024-04-26 11:41:22

尝试这样做:

{% for item in list %}   
    {{ item|safe }} 
{% endfor %}

为了分解这里的一些语法,{% %}通常引用语句(比如{% if something %}或{})。{{ }}用于打印某些内容(如{{ item }}或{})。当您向print语句添加一个|时,它将指示jinja2对它前面的对象应用一个过滤器。例如,|safe表示前面提到的对象是“安全”的html,不需要转义。在

相关问题 更多 >