I believe I have a fundamental misunderstanding as to how Jinja templates are rendered. I am trying to pass data to my flask backend via a GET request, run a query given that data as a parameter, and then render a jinja child template with the given queried information.
Here is my simple javascript function, the click registers, and it runs the query just fine. I don't even believe I need anything in the success tag.
$( "td" ).click(function() {
var comname = $(this).text();
$.ajax({
type: 'GET',
url: "/getSightings",
data: {name: comname},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var result =data.result;
}
});
});
Here I format the result as a JSON dict and attempt to render sighting.html. My "base" html is called home.html, which I render immediately upon @app.route('/')
@app.route('/getSightings')
def getSightings():
js = request.args.get('name')
with conn:
print("this is the data" + js)
sql = ('SELECT PERSON, LOCATION, SIGHTED, GENUS, SPECIES '
'FROM SIGHTINGS AS S, FLOWERS AS F '
'WHERE S.NAME = F.COMNAME '
'AND NAME = ?'
'ORDER BY S.SIGHTED DESC '
'LIMIT 10; ')
cur = conn.cursor()
cur.execute(sql, (js, ))
r = [dict((cur.description[i][0], value) \
for i, value in enumerate(row)) for row in cur.fetchall()]
return render_template('sighting.html', result=r)
This is my home.html where I attempt to link to the child template
<div id="sighting" class="background p-2">
{% block sighting %}{% endblock %}
</div>
And this is my sighting.html
{% extends "home.html" %}
{% block sighting %}
<script type="text/javascript">
console.log("loaded");
</script>
{% if result%}
<h2 class="flower-name">PLAINTEXT</h2>
<div class="table-wrapper-scroll-y wrap">
<table class="table table-hover" id="sightingsTable">
<tbody>
{% for item in result %}
<tr>
<td>{{item["PERSON"]}}</td>
<td>{{item["LOCATION"]}}</td>
<td>{{item["SIGHTED"]}}</td>
<td>{{item["GENUS"]}}</td>
<td>{{item["SPECIES"]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p>Didn't work</p>
{% endif %}
{% endblock %}
No errors are given, but the template is never rendered and the console.log never functions. So I am confused as to how I can conditionally have html rendered using flask. If I replace the above home.html with {% include sighting.html %}, the html is rendered, but it does not have the data from the query (obviously) so it just has the default {elseif} value I gave it.
EDIT: I understand how to change html with jquery. But based on flask documentation I was under the impression that you can render dynamic html using jinja2 and flask templates. If the the workaround is "just use the ajax form and jquery to implement the changes" then thats fine, I will re-evaluate. But is there no way to, on a condition, call a route and render a template based on that route.