It was recently that I tried to use AngularJS with Python Flask web application. But it didn’t worked out straight away. While trying to browse the HTML template files straight from the browser everything worked fine but it rendered nothing while run using Flask server. And there was not a single error in the browser console too. So, it was obvious it had something to do with Python Flask. Why AngularJS Not Working in Python Flask web app ?
Also read : Creating a Web App using Python Flask and MySQL.
The Problem :
Let’s start by creating a simple Python Flask app. Make sure you have python and flask installed. Create a project directory called FlaskAngularApp. Inside the project directory create a file called app.py.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def showDefault():
return render_template('index.html')
if __name__ == "__main__":
app.run()
Create a folder called templates inside the project folder and add the index.html file. App the following code to index.html file :
AngularJS Flask App
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.message = "Howdy !!";
}])
{{message}}
Now if you save the changes and try running the python flask app, the url http://localhost:5000/showDefault wouldn’t display the message.
Why AngularJS Expression {{}} Doesn’t Work in Python Flask
In python flask we have used render_templates for rendering the templates. By default Flask uses Jinja2 engine to render the templates and Jinja2 also uses double curly braces {{ }} to insert values. Hence, AngularJS Not Working in Python Flask web app.
Solution to the Problem
The ideal solution to the above problem is to modify the start and end interpolation tags in AngularJS, so that it doesn’t use double curly braces. You can do that using the interpolateProvider service. Modify the AngularJS code as shown :
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.message = "Howdy !!";
}])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//').endSymbol('//');
});
As seen in the above code, we have modified the interpolation start and end with a double forward slash instead. Inside the HTML code, modify the span as shown:
Message is //message//
Another solution would be to enclose the AngularJS double curly brace in single quotes and pass it in the Jinja2 double curly braces.
Message is {{ '{{message}}' }}
Wrapping It Up
In this article we saw, why AngularJS Not Working in Python Flask because of the double curly brace issue. We saw how to solve the double curly brace issue by modifying the start and end tag using the interpolateProvider service. Have you guys encountered any other issue while trying to use AngularJS in Python Flask. Do let us know in the comments below.