This question already has answers here:
Is it possible to use AngularJS with the Jinja2 template engine?
(2 answers)
Closed 6 years ago.
I am trying to implement AngularJs to my flask project. In my app.py I have this code to render a test site:
#app.route('/test/')
def test():
return render_template('test.html')
And in the test.html I have this:
<!DOCTYPE html>
<html lang="en" data-ng-app>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<title>Flask-Triangle - Tutorial</title>
</head>
<body>
<label>Name:</label>
<input type="text" data-ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{ yourName }}!</h1>
</body>
</html>
When I type in the input field nothing is happen..
I have checked that the angular.min.js is correctly loaded.
Is there something I have to do in app.py to get this work?
Flask uses jinja as its templating language which also uses {{ variable }}
so when flask renders the templates {{ yourname }} just becomes an empty string since yourname is not a context variable in the current render
to fix this you can use flask-triangle
http://flask-triangle.readthedocs.org/en/develop/tutorial/part1.html
which provides a template filter
{{ yourname | angular }} that will ensure the template is rendered correct for angular
you could also use escaped brackets inside the brackets (but this is much uglier I think)
{{ '{{ yourname }}' }}
Another way to fix this is that you can wrap the entire test.html contents with {% raw %} at the top, and {% endraw %} at the bottom. This will tell jinja not to do anything special in this. This way would only be good if you are not planning on using jinja at all. Using this would also make it a bit nicer to write with, as you no longer have to add in the fixes that Joran Beasley suggested.
Example:
{% raw %}
<!DOCTYPE html>
<html>
<head>
<!-- HEADER STUFF -->
</head>
<body>
<!-- Normal AngularJS code and syntax -->
</body>
</html>
{% endraw %}
Related
Using flask, I'm passing in a list of dictionaries to one of the pages. One of the variables contains html text (ex:var x = <h1>hello</h1>). How would I get it to display as hello rather than just print out "<h1>hello</h1>"? Here's my code so far (post.description has the html variable; It's equal to <h1>hello</h1>):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% for post in posts %}
<p>{{post.title}}<p>
{{post.description}}
{% endfor %}
</body>
</html>
You can use safe to render the HTML code with Jinja.
Example: {{ post.description | safe }}
So this is my issue: I have a Python string that contains both HTML and Django Template Tags and want to inject it into a base HTML file when I go to that page. Although, when I go to the page, all the HTML renders, but the Django Template Tags do not, and are treated literally as strings?
Here is a simplified example of the issue:
Views.py
def page(request, code):
html = {
'code': code
'html': """<p>Hello world {{ code }}</p> <script src="{% static 'appName/javascript_code_example.js' %}"></script>"""
}
return render(request, 'base.html', html)
base.html
{% load static %}
...
{{ html | safe }}
...
And all I will see when I run the app on my local machine with python3 manage.py runserver and go to the URL that renders base.html is Hello world {{ code }}, and the Javascript code is not executed. Instead of {{ code }} I'd like to see the actual value of the 'code' key in the html dictionary in the Views.py file.
If my base.html file is as follows:
{% load static %}
...
<p>Hello world {{ code }}</p>
<script src="{% static 'appName/javascript_code_example.js' %}"></script>
...
Then the Javascript will be enabled and I will see Hello world value_of_code_variable on the screen.
you have to load the python script that has the template library functions.
Also, Why are you rendering a string into html as opposed to creating an html template? (html file with template syntax)?
The Django template engine will not render (parse) template code inside injected strings. For this to happen, you have to manually render the template code by either:
instantiating a Template object and passing the resulting string to your base.html,
or ideally by moving the value of your html context variable to a template file, and using render_to_string().
If you decide to go for the last one, you should definitely consider using the include template tag in your base.html (instead of manually rendering using render_to_string()), as it reduces the amount of manual work and is the preferred way of rendering template code inside another template.
You can use file writing to do this task.
Make a newfile.html in templates folder and you can do thusly
Views.py
html_tag = "{% extends \"yourapp/base.html\"%}"+"{% block content %}"
html_tag +="<p>Hello world {{ code }}</p> <script src=\"{% static \"appName/javascript_code_example.js\" %}\"></script>"
html_tag +="{% endblock content %}"
html_file = open('yourapp/templates/yourapp/newfile.html', "w")
html_file.write(html_tag)
html_file.close()
html = {
'code': code
}
return render(request, r'yourapp\newfile.html', html)
In base.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Your base code</p>
<!--The part of code you want to retrieve from views.py file-->
{% block content %}{% endblock content %}
</body>
</html>
Am very much new to Flask & Python, so want to understand/clear my concepts. I have a webpage which i created using flask & wtforms. Html page is very simple having just single field & a submit button. I want to call a python script (test.py) itself or python function(pythonfunction()) when submit button is clicked. Also Is there a way from the webpage,whatever i enter , i can pass as an attribute to that python script (test.py)? help appreciated
**app.py**
from flask import Flask , render_template,flash,redirect,url_for,session,logging,request
from wtforms import Form,StringField,TextAreaField,PasswordField,validators,SelectField,TextAreaField
from wtforms.widgets import TextArea
import subprocess
import test
app=Flask(__name__)
#app.route ('/')
def index():
return render_template('home.html')
class testpython(Form):
testenter=StringField('Enter something')
#app.route ('/testpage',methods=['GET','POST'])
def testpage():
form=testpython(request.form)
return render_template('testpage.html',form=form,python=testfunc(testenter))
if __name__ == '__main__':
app.run(debug=True)
**test.py**
def pythonfunctiontest (self):
print data #<something i can print here from that text field in webpage>
return "all good"
**testpage.html**
{% extends 'sec_layout.html'%}
{% block body %}
{% from "includes/_formhelpers.html" import render_field %}
<form method="POST" action ="">
<div class="form-group">
{{render_field(form.testenter,cols="1", rows="5",class_="form-control")}}
</div>
<div class="input-bar-item input-bar-item-btn">
<button class="btn btn-info">Submit</button>
</div>
</form>
{% endif %}
{% endblock%}
sec_layout.html
<!DOCTYPE <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>MY PAGE-TEST</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class= "container">
{% block body %}{% endblock%}
</div>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" </script>
</body>
</html>
The question is very general so I will try and give you a steer and perhaps you might revisit this question later with a little more clarity.
Flask asks a server and renders webpages. I.e. it executes some code on the server and passes it to the client web browser. The client web browser can then execute client side code (i.e. Javascript) as the user is browsing and can pass data back to the server using submit forms (to different Flask routes) or via JavaScript AJAX requests (again to other Flask routes). So if you want to execute python script based on some input you will need a separate route.
Here is a simple example of an index page and a second route that will execute something else:
#app.route('/index')
def index():
""" very basic template render """
return render_template('index.html')
#app.route('/data-submit', methods=["POST"])
def calc():
data = request.form.information.data
# do something with data..
x = data + data
return render_template('new_page.html', x)
========= (index.html)
<html>
<body>
<form action="{{ url_for('app.calc') }}" method="POST">
<input name="information" type='text'>
<button name="submit">
</form>
</body>
</html>
Wrap whatever temp.py is doing in a function.
Place it in the same directory as flask.py. Call import temp in flask.py, then use temp.myfunction().
This question already has answers here:
Flask-WTF - validate_on_submit() is never executed
(8 answers)
Closed 4 years ago.
Here is the class I created, model of the flask mega tutorial's RegistrationForm
class eyeReaderInput(FlaskForm):
article = StringField('Article')
submit = SubmitField('Enter')
And I've implemented that class in this view:
#app.route('/eyereader', methods=['GET', 'POST'])
def eyereader():
form = eyeReaderInput()
sTuple = ()
if form.validate_on_submit():
string = wikipedia.page(form.article.data)
for chunk in textwrap.wrap(string, 15):
sTuple += (chunk,)
return render_template('eyereader.html', string = sTuple, form = form)
else:
return render_template('eyereader.html', form = form)
with this being my template of eyereader.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if string %}
<p><span>
{% for s in string %}
[{{s}}]<pre class="tab"></pre>
{% endfor %}
</span></p>
{% else %}
<p>Please input an article name</p>
<form action = "" method = "post">
<p>{{ form.article.label}}<br>
{{ form.article() }}</p>
<p>{{ form.submit() }}</p>
</form>
{% endif %}
</body>
</html>
What I'm hoping to do is for the user to initially access the eyereader site using a 'GET' request (which is what happens when I look at my console), and once the user inserts the wikipedia article he wishes to read, it sends a 'POST' request with a new string parameter which will make {% is string %} true and instead show the wikipedia text.
However when I'm testing this, both 'GET' and 'POST' requests end up going to the input page. Does anyone know what I may be able to change to get this to work? Thanks.
Option #1: Use two templates to handle the conditional content, tying each template to a different form action (GET/POST).
#app.route('/eyereader')
def show_template():
return render_template("eyereader.html")
Option #2: Use JavaScript to dynamically populate content as needed.
<script type="text/javascript">
$('#my_object').on('change', function() {
var selected = $( "#my_object condition:true" ).text();
if(selected == "yes")
$(Do_Something_Here)
});
</script>
I've got a simple flask app, with a templates folder with a bunch of html files that are created by a separate program. I want to (1) serve each of these html files by hitting localhost:8888/<html_filename> and
(2) create a directory with hyperlinks to these endpoints on my main / endpoint.
Thoughts on how I could get a jinja template to create links to those endpoints? Heres what I've been thinking.
Flask App:
#app.route('/')
def index():
reports = [f_name for f_name in os.listdir("templates") if f_name.endswith(".html")]
return render_template("index.html", reports=reports)
#app.route('/<report>')
def render_report(report):
return render_template(report+'.html')
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Report Directory</title>
</head>
<body>
<ul>
{% for r in reports %}
<li>
{{ r }}
</li>
{% endfor %}
</ul>
</body>
</html>
Off the top of my head and not tested in any way define a route along the lines of the following:
#route("/<string:slug>/", methods=['GET'])
def page(self, slug):
if slug_exists_as_a_html_file(slug):
return render_template(slug)
abort(404)
The function (or inline it) )slug_exists_as_a_html_file needs to return True if the slug matches a valid html template file, otherwise false.
To generate your report listing use something like :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Report Directory</title>
</head>
<body>
<ul>
{% for r in reports %}
<li>
{{ r }}
</li>
{% endfor %}
</ul>
</body>
</html>