Using Flask with vue.js as a frontend framework

Update: I will be updating this post with my experience using Flask and Vue.js as a frontend framework.

Flask has become my Python framework of choice and I have been trying to use Vue.js as the front-end JS framework for an app with flask powering the backend API.

The only snag is that both Flask and Vue.js both use the double handlebar notation i.e. “{{}}” For variable interpolation in HTML, So using them both in an app could cause some headaches.

After some googling on the issue, I discovered that you could actually do this to make them play well together:

You have 2 options, modify either Flask or Vue.js

In your view file, i.e. the Python controller script, do this:

from flask import Flask, render_template, request

class CustomFlask(Flask):
jinja_options = Flask.jinja_options.copy()
jinja_options.update(dict(
block_start_string='$$',
block_end_string='$$',
variable_start_string='$',
variable_end_string='$',
comment_start_string='$#',
comment_end_string='#$',
))

app = CustomFlask(__name__)

@app.route("/")
def index():
return render_template("index.html")

if __name__ == "__main__":
app.run()

Or add this to your layout.html template file:


https://npmcdn.com/vue/dist/vue.js

Vue.config.delimiters = ["${", "}"];

and add the custom javascript file holding the Vue instance that will target parts of your DOM to the end of the HTML template file.

I actually prefer changing the Vue.js delimiters than changing Jinja2 delimiters because I am used to using the “{{}}” notation and it will make your old code backward compatible with Vue.js

It works because you subclass the Flask class imported from the flask module and modify it by changing the Jinja delimiters. I made my setup closely mirror “Templator” which is the name of the templating system used in web.py, a small Python web framework written by Aaron Swartz.

If you are a frontend dev, give Vuejs a spin, it has an almost nonexistent learning curve, so give it a trial today.

Advertisements

One thought on “Using Flask with vue.js as a frontend framework

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s