ToscaWidgets can inject resources that have been registered for injection in the current request.

Usually widgets register them when they’re displayed and they have instances of tw.api.Resource declared at their tw.api.Widget.javascript or tw.api.Widget.css attributes.

Resources can also be registered manually from a controller or template by calling their tw.api.Resource.inject() method.

When a page including widgets is rendered, Resources that are registered for injection arre collected in request-local storage area (this means any thing stored here is only visible to one single thread of execution and that its contents are freed when the request is finished) where they can be rendered and injected in the resulting html.

ToscaWidgets’ middleware can take care of injecting them automatically (default) but they can also be injected explicitly, example:

>>> from tw.api import JSLink, inject_resources
>>> JSLink(link="").inject()
>>> html = "<html><head></head><body></body></html>"
>>> inject_resources(html)
'<html><head><script type="text/javascript" src=""></script></head><body></body></html>'

Once resources have been injected they are popped from request local and cannot be injected again (in the same request). This is useful in case injector_middleware is stacked so it doesn’t inject them again.

Injecting them explicitly is neccesary if the response’s body is being cached before the middleware has a chance to inject them because when the cached version is served no widgets are being rendered so they will not have a chance to register their resources.


tw.core.resource_injector.inject_resources(self, html, resources=None, encoding=None, render_filter=None, environ=None)

Injects resources, if any, into html string when called.


Ignore the self parameter if seeing this as tw.core.resource_injector.inject_resources() docstring since it is an alias for an instance method of a private class.

html must be a encoding encoded string. If encoding is not given it will be tried to be derived from a <meta>.

Resources for current request can be obtained by calling tw.framework.pop_resources(). This will remove resources from request and a further call to pop_resources() will return an empty dict.


tw.core.resource_injector.injector_middleware(app, render_filter=None)

Middleware that injects resources (if any) into the page whenever the output is html (peeks into Content-Type header).

Normally you don’t have to stack thi yourself because tw.core.middleware.ToscaWidgetsMiddleware does it when it is passed the inject_resources flag as True (default).