This question already has answers here:
Is it possible to use AngularJS with the Jinja2 template engine?
(2 answers)
Closed 4 years ago.
I'm using flask to render index page
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
I'm sending the results in an ajax call made to an flask REST API. I'm able to build table using Jquery but If I'm using angularjs ng-repeat for a table like below
<table>
<tr data-ng-repeat="r in regResults">
<td>{{r.TCID}}>
</tr>
</table>
I'm getting the below error
[2018-01-30 16:50:32,833] ERROR in app: Exception on / [GET]
UndefinedError: 'r' is undefined
That's because Angular and Jinja2 use {{}} as template tags to print out variables. Jinja2 processes the template before it's rendered by the browser (and eventually picked up by Angular). The simplest solution is to enclose the block in {% raw %} like this:
{% raw %}
<table>
<tr data-ng-repeat="r in regResults">
<td>{{r.TCID}}>
</tr>
</table>
{% endraw %}
This tells jinja2 not to interfere with that section of the template.
If you find yourself with too many {% raw %} tags it might be time to separate your frontend from the backend and communicate over an API.
Related
This question already has answers here:
Create dynamic URLs in Flask with url_for()
(6 answers)
Closed 8 months ago.
I am trying to creating dynamic url in html and routing all "orders/<key_id[0]>" to flaks app.
On the browser hyperlink should be link to name but it should route as "orders/<key_id[0]>"
Tried a lot of thing couln't manage to generate href with key_id variable with it.
Trying to create something like
{{key_id[0]}<p>{{name[0]}}</p></td>
My Base Html Code:
{% for name, sample, date, coord_x, coord_y, key_id in zipped_ %}
<tr>
<td><p>{{name[0]}}</p></td>
<td>{{sample[0]}}</td>
<td><span class="badge badge-danger">{{date[0]}}</span></td>
<td>
<div class="sparkbar" data-color="#00a65a" data-height="20">{{coord_x[0]}},{{coord_y[0]}}</div>
</td>
</tr>
{% endfor %}
Flask App Routing:
#views.route('/orders')
#views.route('/orders/<key_id>', methods=['GET', 'POST']) # ordersda birşey yazdın ama indexten bir post ya da get gelmiyor sanki
def orders():
print(key_id)
#mycursor.execute("SELECT * FROM processed_data WHERE primary_key IN (%s)",(key_id))
#zip_q = mycursor.fetchall()
return render_template("orders.html", zip_q=zip_q)
There are many ways to do it depending on your Jinja version. The "most compatible" one is to use string formatting with urlencode filter
{{key_id[0]}<p>{{name[0]}}</p>
I have found the answer at last.
<a href= {{ url_for('views.orders' , key_id=key_id[0]) }} <p>{{name[0]}}</p></a></td>
with url_for i can dynamically edit the link and for passing variable to flask:
#views.route('/orders')
#views.route('/orders/<key_id>', methods=['GET', 'POST'])
def orders(key_id):
print(key_id)
i can get the key_id variable in the flask app.
How to render jinja code on template?
For instance, I have a route that need to render jinja code on the given HTML template like this:
from app import app
from flask import render_template
from jinja2 import Template
#app.route('/View/Package')
def getView():
HtmlDesc="""
<div class="codehilite"><pre><span></span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">/</span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">/</span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">.</span><span class="n">py</span>
</pre></div>
"""
return render_template('package.html', html=Template(HtmlDesc).render())
On the template, I tried to escape jinja code with {% raw %}..{% endraw %} and {% filter escape %} .. {% endfilter %} as documented here but it still does not work:
<h1>Project Description</h1>
<div class="project-description">
{% raw %}{% filter escape %}{{html|safe}}{% endfilter %}{% endraw %}
</div>
</div>
With exception:
TemplateSyntaxError: unexpected '<'
I know the error is at {{</span><span... and class="p">}}, value of HtmlDesc, therefore I am looking for a proper way to escape these kind of characters of jinja in order to render this jinja code on template correctly. Thanks.
Added
What I am trying to achieve is I want the html and jinja code of HtmlDesc to be interpreted and render properly on web browser. In my real application, the text above is not a fixed value as in above example snippet, it reads value from text file README which includes inside python package and converted into HTML code. The example text above it is read from python package cookiecutter.
Add a | safe to the end of whatever you want to display. It will render it out. Make it a string too.
Inside the template you seem to be missing the |safe in the {{ }} inside the Markup
Also you have to remove the Template() to make sure that the whole string is escaped
I am building a python web app hosted on pythonanywhere following this tutorial loosely. I am modifying the resulting application to fit my own goal.
Here is my python code that I am using to pass variables to a HTML document in order for them to be added to a table using a for loop:
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["DEBUG"] = True
productnames = []
reviews = []
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("main.html", reviews=reviews, productnames=productnames)
reviews.append(request.form["review"])
productnames.append(request.form["products"])
return redirect(url_for('index'))
Using the following code within my HTML, I am looping through that list and adding each item to the table:
{% for review in reviews %}
<tr>
<td></td>
<td>{{ review }}</td>
<td></td>
</tr>
{% endfor %}
And this works, however, I am trying to iterate through multiple lists and found various statements saying that the zip function was what I was looking for so I changed my HTML code to the following segment and it no longer works.
{% for review, product in zip(reviews, productname) %}
<tr>
<td>{{ product }}</td>
<td>{{ review }}</td>
<td></td>
</tr>
{% endfor %}
From python anywhere, the error page says "Error code: Unhandled Exception", and the error log through the pythonanywhere dashboard says:
2018-04-24 12:57:23,957: File "/home/FdScGroup/cloudapp/templates/main.html", line 43, in top-level template code
2018-04-24 12:57:23,957: {% for review, product in zip(reviews, productnames) %}
How do I get this to work?
Any help appreciated, thank you.
zip() is a python function, not a function to be executed in the template language of Flask (Jinja2).
So apply zip() in the view and pass the result to the template:
return render_template("main.html", reviews_products=zip(reviews, productnames))
Then apply this trick:
how to iterate over a list of list in jinja
in the template.
so im new to Python and Django, im wondering if there is a concept like a template for the whole app/site like
<html>
...
<body>
{% content_goes_here %}
</body>
and than you got your views:
<tr>
{% name %}
</tr>
..
so i can use views as building blocks for my site but have a global template that does all the css/head/script/html stuff.
I know this concept from cakephp for example. How is this done in Django?
You can do this by using template inheretance
I'm using the (awesome) Flask framework to build a website and I now have a problem with html not being rendered properly. I've got a line in my template with an if-else depending on whether the public variable is True:
{{ theInfo if public else '<span style="background-color: green;">this info is hidden</span>' }}
Unfortunately, this simply displays the html in the browser, instead of rendering it. Do I need to somehow let Jinja know that its html should be rendered?
All tips are welcome!
By default Jinja escapes the passed data. Therefore you need to explicitly tell Jinja that data is safe to use:
{{ theInfo if public else '<span style="background-color: green;">this info is hidden</span>' | safe }}
If you want to display different html based on a value you need to first send this value in your call to render_template
python
def view():
variablename = True
return flask.render_template('page.html', public=variablename)
To check this value you add an if statement inside curly brackets, see code below
html
{% if public %}
<p>Public is true!</p>
{% else %}
<span ..../>
{% endif %}
A good first step is to go through the tutorial by Miguel Grinberg. http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world