在前端世界中公开并执行django url的反向查找。
django-js-routes的Python项目详细描述
django js routes是一个django应用程序,允许公开和执行 客户端的django命名url模式。
目录
Main requirements
python 3.4+,django 2.0+。
Installation
要安装django js路由,请使用pip命令,如下所示:
$ pip install --pre django-js-routes
安装包后,您必须将应用程序添加到 项目设置模块:
INSTALLED_APPS=(# all other apps...'js_routes',)
然后,您可以定义要向客户端公开的url模式或url命名空间 正在设置JS_ROUTES_INCLUSION_LIST设置。此设置允许定义应为 通过生成和/或导出的javascript序列化并提供给客户端 帮手。此列表应仅包含URL模式名称或命名空间。下面是一个示例:
JS_ROUTES_INCLUSION_LIST=['home','catalog:product_list','catalog:product_detail',]
请注意,如果此列表中包含命名空间,则所有基础URL都将提供给 客户端通过生成的javascript助手。Django JS Routes在 感觉到only您在此包含列表中配置的url将在 客户端。
一旦配置了要公开的url列表,就可以将{% js_routes %}标记添加到基 模板,以确保javascript助手在您需要时可用:
{% load js_routes_tags %} <html><head></head><body><!-- At the bottom of the document's body... --> {% js_routes %} </body></html>
Usage
然后,通过JS_ROUTES_INCLUSION_LIST设置配置的url模式可以是 使用生成的window.reverseUrl函数反转,可以使用 使用reverse的“相同”方式 Django侧:
window.reverseUrl('home');window.reverseUrl('catalog:product_list');window.reverseUrl('catalog:product_detail',productId);window.reverseUrl('catalog:product_detail',{pk:productId});
Advanced features
Inserting only the serialized URLs in Django templates
默认情况下,{% js_routes %}template标记只允许触发 序列化的url(存储在window对象的javascript对象中)并包含 使用django的html中的javascript url解析器函数 static模板标记。 实际上,{% js_routes %}语句的标准用法相当于:
{% js_routes routes_only=True %} <scriptsrc="{% static 'js/routes/resolver.js' %}"></script>
routes_only选项只允许在 {% js_routes %}。它使您能够包含随附的javascript url解析器 django js使用另一个static语句路由。这还允许您缓存 {% js_routes routes_only=True %}语句(这样序列化的url就不会 为每个请求生成)。
Dumping the Javascript routes resolver
如前所述,{% js_routes %}template标记触发生成序列化的 并在最终的html中包含客户端url解析器。这种行为的一个缺点是 每次呈现html模板时都需要生成序列化的url。
相反,可以只转储序列化url的整个列表和url解析器函数 变成一个javascript模块文件。这可以通过使用^{tt16}来实现$ 命令,可按如下方式使用:
$ python manage.py dump_routes_resolver --format=default --output=my_exported_resolver.js
--output选项允许指定序列化路由和解析器函数指向哪个文件 应该在--format选项允许指定要使用的javascript格式时保存。
--format接受以下值:
- default将路由作为与window对象关联的对象包含,而 url解析器可通过window.reverseUrl函数使用(这对应于 标准使用{% js_routes %}template标记提供的行为
- es6a}允许将路由和url解析器保存为es6模块,其中reverseUrl 函数是默认导出
License
麻省理工学院。有关详细信息,请参见LICENSE。