I have been developing a website in Flask and recently have begun refactoring my routes to accommodate an API framework. However, I am having trouble passing JSON data from my API (which comes from calling Flask's jsonify()
on a dict
within the API) into views using Flask's render templates.
For example without the API a view function's return would look like
return render_template('project.html', name=proj.name, description=proj.description, tags = proj.tag_list ...)
with the API, where all the relevant data for a model is contained within a JSON object, I have been attempting something of the form:
return render_template('project.html', jsonobj=api.project.get_project(project_id))
where the associated API function is
def get_project(id):
return jsonify(Project.query.get_or_404(id).to_dict())
However, the data is unable to render in the HTML properly. If I pass in a dictionary to jsonobj instead - i.e., Project.query.get_or_404(id).to_dict()
- the data will render. But I don't want to have to reconvert the JSON to a dictionary as this is an extra step.
Edit: I'm realizing that I perhaps shouldn't be using render_template()
to pass data to the html and populate the page (as found here). It seems like if I'm constructing an API I should be populating my HTML from JavaScript. However I'm not sure what the best way to do this is with Flask, and while I've found some related threads am not sure what the optimal solution is.