我想使用flask-assets来组织我的webassets和mako进行模板化。 Flask-assets通常以下列方式使用jinja:
{% assets "js_all" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
Mako等价物(据我所知)将如下:
% assets 'coffee':
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
% endassets
但是这会导致编译错误:
mako.exceptions.CompileException
CompileException: Unsupported control keyword: 'assets' in file '/index.html' at line: 8 char: 1
有没有办法在Mako中使用自定义控件关键字(如'资产')?
这是我的记录app.py:
import os
from flask import Flask, render_template
from flask.ext import assets
from flask import config
from flask.ext.mako import MakoTemplates
from flask.ext.mako import render_template
app = Flask(__name__)
app.config['ASSETS_DEBUG'] = True
mako = MakoTemplates(app)
env = assets.Environment(app)
# Tell flask-assets where to look for our coffeescript and sass files.
env.load_path = [
os.path.join(os.path.dirname(__file__), 'js'),
os.path.join(os.path.dirname(__file__), 'styles'),
]
coffee = assets.Bundle('**/*.coffee', filters='coffeescript', output="app.js")
env.register('coffee', coffee)
@app.route("/")
def index():
return render_template('index.html', name='mako')
if __name__ == "__main__":
app.run(debug=True)
答案 0 :(得分:2)
好吧,我想出了一个解决方案。您可以通过将环境导入基础模板并对其进行操作来使其工作。
assets.py:
import os
from flask.ext import assets
from app import app
env = assets.Environment(app)
# Tell flask-assets where to look for our coffeescript and sass files.
env.load_path = [
os.path.join(os.path.dirname(__file__), 'js'),
os.path.join(os.path.dirname(__file__), 'styles'),
]
coffee = assets.Bundle('**/*.coffee', filters='coffeescript', output="app.js")
env.register('coffee', coffee)
模板:
<%!
from assets import env
%>
<!doctype html>
<html>
<head>
<title>Hello Flask</title>
<head>
<body>
<h1>Hello Flask</h1>
% for url in env['coffee'].urls():
<script src="${url}"></script>
% endfor
</body>
</html>
可能有办法通过使用MAKO_IMPORTS配置参数来避免导入,但我还没有使用它。
答案 1 :(得分:1)
Flask-Assets只是registers the webassets Jinja extension with Flask's Jinja environment。 WebAssets只发布(在撰写本文时)with an extension for Jinja2,所以如果你想要Mako的资产标签,你将to write one yourself(虽然有人有already written something similar for Pyramid,所以你可以take inspiration from that)。