user706838
user706838

Reputation: 5380

How to take advantage of Flask Blueprints within JavaScript?

My project has the following structure:

run.py
application/
-- __init.py__
-- landing/
-- -- templates/
-- -- -- index.html
-- -- static/
-- -- -- img/
-- -- -- -- photo1.png
-- -- -- -- photo2.png
-- -- -- -- photo3.png
-- -- -- js/
-- -- -- -- script.png
-- -- __init.py__
-- -- models.py 
-- -- views.py 

run.py contains:

from application import app

if __name__ == '__main__':
    app.run(debug=True)

among the other things, application/__init.py__ contains:

from application.landing.views import landing
app.register_blueprint(landing)

application/landing/__init.py__ contains:

# coding:utf-8
from views import *

application/landing/models.py is empty

application/landing/views.py contains:

from flask import render_template , Blueprint

from application import app

landing = Blueprint('landing' , __name__ , static_url_path='/landing/static' , static_folder='./static' , template_folder='./templates')

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

Now, in index.html, I define every css and jpg file as:

{{ url_for('landing.static' , filename='css/bootstrap.min.css') }}

and

{{ url_for('landing.static' , filename='img/logo.png') }}

respectively. so far so good. However, there is a file under application/landing/static/js/main.js that requires three static files as: //Fullscreen Background Image Slideshow $.backstretch([ "landing/static/img/bg/01.jpg", "landing/static/img/bg/02.jpg", "landing/static/img/bg/03.jpg" ], {duration: 3000, fade: 750});

Apparently, I don't want to hard - code these files but to use Blueprints instead or in other words, something like this:

    $.backstretch([
        "{{ url_for('landing.static' , filename='img/bg/01.jpg') }}", 
        "{{ url_for('landing.static' , filename='img/bg/02.jpg') }}",
        "{{ url_for('landing.static' , filename='img/bg/03.jpg') }}"
    ], {duration: 3000, fade: 750});

BUT as you might guess, this returns 404 errors:

127.0.0.1 - - [31/Aug/2015 16:47:42] "GET /%7B%7B%20url_for('landing.static'%20,%20filename='img/bg/01.jpg')%20%7D%7D HTTP/1.1" 404 -
127.0.0.1 - - [31/Aug/2015 16:47:42] "GET /%7B%7B%20url_for('landing.static'%20,%20filename='img/bg/02.jpg')%20%7D%7D HTTP/1.1" 404 -
127.0.0.1 - - [31/Aug/2015 16:47:42] "GET /%7B%7B%20url_for('landing.static'%20,%20filename='img/bg/03.jpg')%20%7D%7D HTTP/1.1" 404 -

So any ideas?

Upvotes: 0

Views: 310

Answers (1)

lipponen
lipponen

Reputation: 753

You could try to use Flask-jsglue plugin http://stewartpark.github.io/Flask-JSGlue/

In just include plugin

<head>
{{ JSGlue.include() }}
</head>

Then in the actual javascript code:

Flask.url_for("landing.static", {"filename": "img/bg/01.jpg"})

Upvotes: 1

Related Questions