Django:动态生成JS是个好主意吗? [英] Django : Is it a good idea to generate JS dynamically?

查看:158
本文介绍了Django:动态生成JS是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我为Django项目编写JS文件时,我当然会做一些AJAX调用,目前这些调用的URL是硬编码的(这非常丑陋)。

When I write my JS files for a Django project, of course I do some AJAX calls, and for the moment the urls for those calls are hard-coded (which is very ugly).

我正在考虑使用django(而不是Apache)提供的JS文件,所以我可以利用模板标签( {%url%}

I was thinking of having the JS files served by django (instead of Apache), so I could take advantage of the template tags ({% url %} !!!).

有没有理由不该这样做?

Is there a reason why I shouldn't do this ?

或有没有正确的方法?

(我可以给出至少一个:它会消耗很多时间重新发送没有改变的JS文件,什么很棒的是有一个应用程序在重新启动django服务器时生成文件,并且在静态后服务它们。)

(I can give a least one : it will consume a lot of time resending JS files that haven't changed. What would be great is to have an application that generates files when restarting django server, and serves them statically after !)

推荐答案

djangopackages 的资产管理器应用程序中,发现django-medi agenerator 提供了这个功能,即使它没有很好的记录:你可以生成你的js或css文件作为django模板,然后静态地(他们也捆绑,缓存被管理等...所以两个有一只石头的鸟+它真的很容易设置!)

I searched deeper in those asset manager applications from djangopackages, have found out that django-mediagenerator provides that feature, even if it is not well documented : you can generate your js or css files as django templates, and then serve them statically (they are also bundled, and caching is managed etc ... so two birds with one stone + it is really easy to set-up !).

为了将JS文件生成为django模板(设置好后,$ code> django-mediagenerator ),只需添加过滤器:

In order to have JS files generated as django templates (after having set-up django-mediagenerator), just add the filter :

ROOT_MEDIA_FILTERS = {
    'js': 'mediagenerator.filters.template.Template',
}

您的设置。

这篇关于Django:动态生成JS是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆