admin管理员组

文章数量:1294306

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()

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()
Share asked Feb 12, 2015 at 20:22 fhbifhbi 7527 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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 plete 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.

本文标签: javascriptRendering Jinja template in Flask following ajax responseStack Overflow