Jinja2 到 JavaScript 编译器
项目描述
JsJinja: 在JS中渲染Jinja2模板
JsJinja 允许您在JavaScript中使用您的 Jinja2 模板。它 无限制地将Jinja2模板编译成JavaScript。
js可以通过命令行 jsjinja <template file> 或通过模板中的 {% jsjinja %} 标签生成。
您可以使用
模板继承(Include,Extends,Blocks,super等)
导入
宏
测试
过滤器
标签
唯一的例外是您不能使用像 {% customtag %}{% endcustomtag %} 这样的自定义标签。
安装
首先,您必须执行
pip install jsjinja
摘要
以下是一个Jinja模板的小示例
{% extends 'base.html' %}
{% block title %}Memberlist{% endblock %}
{% block content %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
{% endblock %}
以下是编译后的JavaScript模板
(function() {
Jinja2.extends(Template, Jinja2.Template);
Jinja2.registerTemplate("readme_template.tmpl", Template);
function Template() {return Template.__super__.constructor.apply(this, arguments);};
Template.prototype.root = function (context) {
var buf = "";
var parent_template = Jinja2.getTemplate("base.html", "readme_template.tmpl");
for (name in parent_template.blocks) {
var parent_block = parent_template.blocks[name];
context.blocks[name] = context.blocks[name] || [];
context.blocks[name].push(parent_block)
}
buf += parent_template.root(context);
return buf;
}
Template.prototype.block_content = function (context) {
var buf = "";
var l_users = context.resolve("users");
buf += "\n <ul>\n ";
var l_user = undefined;
var t_1 = l_users;
for (var t_2= 0, t_3 = t_1.length; t_2<t_3; t_2++) {
l_user = t_1[t_2];
buf += '\n <li><a href="';
buf += l_user['url'];
buf += '">';
buf += l_user['username'];
buf += '</a></li>\n ';
}
l_user = undefined;
buf += "\n </ul>\n";
return buf;
}
Template.prototype.block_title = function (context) {
var buf = "";
buf += "Memberlist";
return buf;
}
return Template;
})()
安装
要开始使用JsJinja,只需将 jsjinja.ext.JsJinjaExtension 添加到您的Jinja2环境中。
示例
import jinja2
env = jinja2.Environment(extensions=['jsjinja.ext.JsJinjaExtension',])
或者
jinja_env.add_extension('jsjinja.ext.JsJinjaExtension')
用法
生成js模板
安装JsJinja扩展后,您必须生成js模板
print jinja_env.jsjinja.generate('your_template.jinja2')
或者直接转换所有
print jinja_env.jsjinja.generate_all()
或者使用 命令行工具
jsjinja <templates>
渲染js模板
要开始使用模板,您必须包含 jinja2.runtime.js 脚本
<script src="https://raw.github.com/SyrusAkbary/jsjinja/master/jsjinja/lib/jinja2.runtime.min.js"></script>
在包含 jinja2.runtime.js 和生成的js模板之后
html = Jinja2.getTemplate("template.html").render({}})
$('body').html(html)
示例
库附带大量示例,您可以在示例目录中找到它们。
测试
您必须安装pyv8和nose Python包。您可以使用以下方法进行测试:
./test.sh