4

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?

EspenG
  • 537
  • 3
  • 10
  • 20

2 Answers2

12

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 }}' }}

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
9

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 %}
Community
  • 1
  • 1
Burn_E99
  • 1,098
  • 1
  • 17
  • 27