在ajax响应之后在Flask中渲染Jinja模板 [英] Rendering Jinja template in Flask following ajax response

查看:240
本文介绍了在ajax响应之后在Flask中渲染Jinja模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次进入Flask + Jinja,但是过去我使用过很多HandlebarsJS,所以我知道这是可能的,但是我不确定如何使用Flask来完成这个工作:

b
$ b

我正在构建一个应用程序:用户输入一个字符串,该字符串通过python脚本进行处理,结果是ajax返回到客户端/ Jinja模板。 b
$ b

我可以使用$(body)。append(response)输出结果,但这意味着我需要在append中写一些讨厌的html

相反,我想要在处理结果后渲染另一个模板,并在原始模板中追加新模板。



这是可能吗?



My python:

  from flask import Flask,render_template ,请求,jsonify 

从脚本导入*

app = Flask(__ name__)

@ app.route('/')
def index():
return render_template('index.html')

@ app.route('/ getColors')
def add _colors():

user = request.args.get(handle,0,type = str)

返回jsonify(
avatar_url = process_data )


if __name__ =='__main__':
app.run()


解决方案

没有关于您的ajax路由必须返回JSON的规则,您可以像正常路由一样返回HTML。


$ b $

  @ app.route('/ getColors')
def add_colors():

user = request .args.get(handle,0,type = str)

return render_template('colors.html',
avatar_url = process_data(data))

您的 colors.html 文件不需要是完整的HTML页面,它可以是您希望客户端附加的HTML代码片段。那么所有客户端需要做的就是将ajax响应的主体附加到DOM中的相应元素。


This is my first dive into Flask + Jinja, but I've used HandlebarsJS a lot in the past, so I know this is possible but I'm not sure how to pull this off with Flask:

I'm building an app: a user enters a string, which is processed via python script, and the result is ajax'd back to the client/Jinja template.

I can output the result using $("body").append(response) but this would mean I need to write some nasty html within the append.

Instead, I'd like to render another template once the result is processed, and append that new template in the original template.

Is this possible?

My python:

from flask import Flask, render_template, request, jsonify

from script import *

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/getColors')
def add_colors():

    user = request.args.get("handle", 0, type = str)

    return jsonify(
        avatar_url = process_data(data)
    )

if __name__ == '__main__':
    app.run()

解决方案

There is no rule about your ajax routes having to return JSON, you can return HTML exactly like you do for your regular routes.

@app.route('/getColors')
def add_colors():

    user = request.args.get("handle", 0, type = str)

    return render_template('colors.html',
                           avatar_url=process_data(data))

Your colors.html file does not need to be a complete HTML page, it can be the snippet of HTML that you want the client to append. So then all the client needs to do is append the body of the ajax response to the appropriate element in the DOM.

这篇关于在ajax响应之后在Flask中渲染Jinja模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆