# HG changeset patch # User Thierry Florac # Date 1528724452 -7200 # Node ID fb23265528fb1e803da0f18a03e865f668c0add7 # Parent bed6978c453c2004983b4e8853c8b9ae3906bc99 Added "canonical_url" interface and TALES extension diff -r bed6978c453c -r fb23265528fb src/pyams_utils/interfaces/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 +# 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""" diff -r bed6978c453c -r fb23265528fb src/pyams_utils/url.py --- 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)