【问题标题】:Variable is not shown in Flask template变量未显示在 Flask 模板中
【发布时间】:2014-05-10 23:26:03
【问题描述】:

我是模板引擎的新手,需要更聪明的人的帮助。尝试使用 Flask 模板生成搜索结果,遇到了很多痛苦。烧瓶:

@app.route('/*?search', methods=['POST', 'GET'])
    if request.method == 'GET':
        if request.args.get('q'):

            qList = re.sub("[^\w]", " ",  request.args.get('q') ).split()

            htmlA = """
                    <div class="results" > 
                    <p>

                    """
            htmlB = """
                    </p>
                    <br></br>
                    </div>
                    """
            found = None
            for it in qList :
                found = htmlA + RESULT_BLAH_BLAH_METHOD( it ) + htmlB

            return render_template( 'list_of_found_items.html', found=found )

和html模板部分:

<somewhere in html>
    {% block content %}
        {{ found }}
    {% endblock %}
</somewhere in html>

这样,即使结果存在并通过打印到控制台输出进行检查,结果也不会显示在页面上。我错过了什么?谢谢。

【问题讨论】:

  • 什么是L?是空的吗?
  • rez 应该是什么?
  • 谢谢。我刚刚编辑过,但没有显示出来。
  • render_template('...', found) => render_template('...', found=found) 否则模板不知道found 是什么。
  • 这是因为自动转义。 flask 认为您的格式(围绕 qList 值的 for 循环)应该在模板中。将 qList 直接传递给您的模板并在那里进行格式化。

标签: python django-templates flask jinja2 templating


【解决方案1】:

自动转义防止直接在 python 中编写 HTML。您的代码可以重写为:

qList = re.sub("[^\w]", " ",  request.args.get('q') ).split()
return render_template('list_of_found_items.html', items = map(RESULT_BLAH_BLAH_METHOD, qList))

还有下面的模板

<somewhere in html>
    {% block content %}
        {% for item in qList %}
            <div class="results" >
                <p>{{item}}</p>
                <br></br>
            </div>
        {% endfor %}
    {% endblock %}
</somewhere in html>

【讨论】:

  • 由于某种原因 TypeError: 'str' object is not callable - at "map()" 函数。正在寻找原因..
  • 我做了一个简单的列表,它可以在没有“map()”的情况下工作。我可以以其他方式实现我的功能。认为它“已解决”,感谢您的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2011-05-17
  • 2017-06-11
相关资源
最近更新 更多