Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering Jinja template in Flask following ajax response

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()
like image 282
fhbi Avatar asked Dec 24 '22 22:12

fhbi


1 Answers

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.

like image 155
Miguel Avatar answered Dec 28 '22 09:12

Miguel