Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask and AngularJs [duplicate]

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?

like image 959
EspenG Avatar asked Nov 30 '22 10:11

EspenG


2 Answers

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

like image 110
Joran Beasley Avatar answered Dec 04 '22 05:12

Joran Beasley


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 %}
like image 26
Burn_E99 Avatar answered Dec 04 '22 06:12

Burn_E99