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?

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thank you
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 %}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.