質問

While developing "widgets" (objects, which - rendered - use some custom javascript files), I faced the need of creating kind of "included-scripts-manager" (to avoid double inclusion of same JS file when more than one widget is rendered for the view).

My first idea was to write custom template rendering Context which would provide EXTRA_SCRIPTS variable in the template. However I have no idea where should I collect the list of scripts during request processing? I think that's where I'd need singleton object.

Any suggestions?

役に立ちましたか?

解決

If you use singleton you will run into thread-safety issue. E.g. your application run in several threads, one thread process single request, so you global object should be per thread, but singleton is unique per process. You can use threading.local technique like described in this question. It will provide you object that is unique per thread and so per request.

However it's not recommended, so don't use global variables

For your situation with widgets there are Media settings in widgets and forms in Django. https://docs.djangoproject.com/en/1.3/topics/forms/media/

Media objects can also be added together. When two media objects are added, the resulting Media object contains the union of the media from both files.

So you can fight duplicates with media. Also you can combine media right into the template

{{ form.media|add:info_form.media|add:discount_form.media }}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top