Added "canonical_url" interface and TALES extension
authorThierry Florac <thierry.florac@onf.fr>
Mon, 11 Jun 2018 15:40:52 +0200
changeset 189 fb23265528fb
parent 188 bed6978c453c
child 190 0b5f84d9eff4
Added "canonical_url" interface and TALES extension
src/pyams_utils/interfaces/url.py
src/pyams_utils/url.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/interfaces/url.py	Mon Jun 11 15:40:52 2018 +0200
@@ -0,0 +1,28 @@
+#
+# Copyright (c) 2008-2018 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+
+# import packages
+from zope.interface import Interface, Attribute
+
+
+class ICanonicalURL(Interface):
+    """Interface used to get content's canonical URL"""
+
+    def get_url(self, view_name=None, query=None):
+        """Get content's canonical URL"""
--- a/src/pyams_utils/url.py	Fri Jun 08 15:17:28 2018 +0200
+++ b/src/pyams_utils/url.py	Mon Jun 11 15:40:52 2018 +0200
@@ -17,6 +17,7 @@
 
 # import interfaces
 from pyams_utils.interfaces.tales import ITALESExtension
+from pyams_utils.interfaces.url import ICanonicalURL
 
 # import packages
 from pyams_utils.adapter import ContextRequestViewAdapter, adapter_config
@@ -85,3 +86,33 @@
         if context is None:
             context = self.context
         return absolute_url(context, self.request, view_name)
+
+
+def canonical_url(context, request, view_name=None, query=None):
+    """Get resource canonical URL"""
+
+    # if we pass a string to canonical_url(), argument is returned as-is!
+    if isinstance(context, str):
+        return context
+
+    url_adapter = request.registry.queryMultiAdapter((context, request), ICanonicalURL)
+    if url_adapter is None:
+        url_adapter = request.registry.queryAdapter(context, ICanonicalURL)
+
+    if url_adapter is not None:
+        return url_adapter.get_url(view_name, query)
+    else:
+        return absolute_url(context, request, view_name, query)
+
+
+@adapter_config(name='canonical_url', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class CanonicalUrlTalesExtension(ContextRequestViewAdapter):
+    """extension:canonical_url(context, view_name) TALES extension
+
+    A PyAMS TALES extension used to get access to an object's canonical URL from a page template.
+    """
+
+    def render(self, context=None, view_name=None):
+        if context is None:
+            context = self.context
+        return canonical_url(context, self.request, view_name)