Added 'need_resource' TALES extension to include Fanstatic resource from template
authorThierry Florac <tflorac@ulthar.net>
Wed, 03 Oct 2018 15:44:46 +0200
changeset 239 dd66b48f53da
parent 238 29ff8ff964da
child 240 17abf8179280
Added 'need_resource' TALES extension to include Fanstatic resource from template
src/pyams_utils/fanstatic.py
--- a/src/pyams_utils/fanstatic.py	Wed Oct 03 09:36:25 2018 +0200
+++ b/src/pyams_utils/fanstatic.py	Wed Oct 03 15:44:46 2018 +0200
@@ -12,19 +12,14 @@
 
 __docformat__ = 'restructuredtext'
 
-
-# import standard library
-
-# import interfaces
-from pyams_utils.interfaces.tales import ITALESExtension
-
-# import packages
 from fanstatic import Resource
-from fanstatic.core import set_resource_file_existence_checking, render_css, NeededResources
-from pyams_utils.adapter import adapter_config, ContextRequestViewAdapter
+from fanstatic.core import NeededResources, render_css, set_resource_file_existence_checking
 from pyramid.path import DottedNameResolver
 from zope.interface import Interface
 
+from pyams_utils.adapter import ContextRequestViewAdapter, adapter_config
+from pyams_utils.interfaces.tales import ITALESExtension
+
 
 def render_js(url, defer=False):
     return '<script type="text/javascript" src="%s" %s></script>' % (url, 'defer' if defer else '')
@@ -62,7 +57,7 @@
 
 @adapter_config(name='resource_path', context=(Interface, Interface, Interface), provides=ITALESExtension)
 class FanstaticTalesExtension(ContextRequestViewAdapter):
-    """extension:resource_path() TALES extension
+    """tales:resource_path() TALES extension
 
     This TALES extension generates an URL matching a given Fanstatic resource.
     Resource is given as a string made of package name (in dotted form) followed by a colon and by the resource name.
@@ -80,3 +75,27 @@
         module = resolver.maybe_resolve(library)
         resource = getattr(module, resource_name)
         return get_resource_path(resource)
+
+
+@adapter_config(name='need_resource', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class FanstaticNeededResourceTalesExtension(ContextRequestViewAdapter):
+    """tales:need_resource() TALES extension
+
+    This extension generates a call to Fanstatic resource.need() function to include given resource
+    into generated HTML code.
+    Resource is given as a string made of package name (in dotted form) followed by a colon and by the resource name.
+
+    For example::
+
+    .. code-block:: html
+
+        <tal:var define="tales:need_resource('pyams_content.skin:pyams_content')" />
+    """
+
+    def render(self, resource):
+        library, resource_name = resource.split(':')
+        resolver = DottedNameResolver()
+        module = resolver.maybe_resolve(library)
+        resource = getattr(module, resource_name)
+        resource.need()
+        return ''