I'm pretty new to Flask, for what it's worth. I'm using blueprints to break up my code and am trying to use Flask-Assets for serving up asset links. For some reason, though, I can't get Flask-Assets to work within a blueprint.
Code structure:
/modules
/base
__init__.py
__init__.py
/static
# ... stuff
/templates
/layout.html
In /modules/base/__init__.py:
from flask import Blueprint, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.assets import Environment, Bundle
from flask import current_app as app
default = Blueprint('base', __name__)
assets = Environment(app)
css = Bundle('css/bootstrap.min.css')
assets.register('css_all', css)
js = Bundle('js/jquery-1.7.2.min.js', 'js/bootstrap.min.js')
assets.register('js_all', js)
@default.route('/')
def index():
return render_template('index/index.html')
And the base layout has this in it:
{% assets "css_all" %}
<link rel="stylesheet" href="{{ ASSET_URL }}" />
{% endassets %}
{% assets "js_all" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
Actually what I have in /modules/base/__init__.py right now doesn't even work, as it throws "RuntimeError: working outside of application context". If I move the assets code into the index function it does work, but it seems weird to have to repeat that code every time I want to add assets. Is there a better way to do this? Am I missing something?
Edit: Updated /modules/base/__init__.py per codecool's comment, but now it throws an "TemplateSyntaxError: Encountered unknown tag 'assets'" error. I think this one is because the assets object isn't getting passed through to the app.
Edit 2: So taking some advice from how SQLAlchemy does things, I got this to sort of work with the following:
In my main __init__.py:
from flask import Flask
from modules.base import default, assets as base_assets
from flask.ext.assets import Environment, Bundle
app = Flask(__name__)
app.register_blueprint(default)
base_assets.init_app(app)
In base/__init__.py: from flask import Blueprint, render_template, request from flask.ext.assets import Environment, Bundle from flask import current_app as app
default = Blueprint('base', __name__)
assets = Environment(app)
css = Bundle('css/bootstrap2.min.css')
assets.register('css_all', css)
js = Bundle('js/jquery-1.7.2.min.js', 'js/bootstrap.min.js')
assets.register('js_all', js)
The trick here is creating assets in the blueprint, importing it into the base init, and then calling .init_app there. Where this breaks down, however, is in having two blueprints that do this. The last one called always wins out. Maybe it'd be possible to pull this out into some common module or something..