Package: grokcore.view
This package provides support for writing browser pages for Zope
and registering them directly in Python (without ZCML).ContentsSetting upgrokcore.viewExamplesSimple browser pageBrowser page with templateStatic resourcesDirectoryResourceLayers and skinsAPI overviewBase classesView APIDirectivesOtherChanges4.0 (2023-02-16)3.2 (2022-02-16)3.1 (2018-06-13)3.0.3 (2018-01-12)3.0.2 (2018-01-05)3.0.1 (2018-01-05)3.0 (2018-01-03)2.10.2 (2016-02-02)2.10.1 (2014-07-29)2.10 (2014-07-29)2.9 (2014-05-15)2.8 (2012-12-11)2.7 (2012-05-01)2.6.1 (2011-06-28)2.6 (2011-06-28)2.5 (2011-04-04)2.4 (2011-03-01)2.3 (2011-01-04)2.2 (2010-12-16)2.1 (2010-11-03)2.0 (2010-11-01)1.12.1 (2009-09-17)1.12 (2009-09-17)1.11 (2009-09-15)1.10 (2009-09-14)1.9 (2009-07-04)1.8 (2009-07-04)1.7 (2009-05-19)1.6 (2009-04-28)1.5 (2009-04-10)1.4 (2009-04-08)1.3 (2009-01-28)1.2 (2008-10-16)1.1 (2008-09-22)1.0 (2006-08-07)Setting upgrokcore.viewThis package is essentially set up like thegrokcore.componentpackage, please refer to its documentation for details.  The
additional ZCML line you will need is:<include package="grokcore.view" file="meta.zcml" />
<include package="grokcore.view" />Put the first line somewhere near the top of your root ZCML file (but
below the line where you includegrokcore.component’s
configuration) and the second line somewhere next to your other
dependency includes.ExamplesSimple browser pageA browser page is implemented by subclassing thegrokcore.view.Viewbaseclass.  At a minimum, a browser page must
havean associated template (or implement therendermethod for direct
control)a context that it’s registered for as a viewa name (which is, if not specified explicitly, the class’s name in
lower case characters).A browser page that does not use a template but just outputs some
computed data also subclasses thegrokcore.view.Viewbaseclass.
At a minimum, such a view must havea render() methoda context that it’s registered for as a viewa name (which is, if not specified explicitly, the class’s name in
lower case characters).For example, the following class defines a view that’s registered for
all objects and simply prints “Hello World!”:import grokcore.view
import zope.interface

class Hello(grokcore.view.View):
    grokcore.view.context(zope.interface.Interface)

    def render(self):
        self.response.setHeader("Content-Type", "text/plain")
        return "Hello World!"Here we’ve made use of the implicit name feature.  This class will be
available as thehelloview for all objects.  So for instance,
you’ll be able to invoke it with URLs like:http://localhost/some/obj/helloWe could also have spelled this out explicitly:class Hello(grokcore.view.View):
    grokcore.view.context(zope.interface.Interface)
    grokcore.view.name('hello')

    ...Browser page with templateOf course, more than often a view should render HTML which you would
construct using some sort of templating engine.grokcore.viewcomes with built-in support for Zope’s PageTemplate engine.  By
convention, PageTemplate templates end with the.ptextension.So let ourHelloview render HTML instead of plain text, we remove
therender()method from the class and instead we create a
template, e.g. like so:<html>
<body>
  <p>Hello <span tal:replace="request/principal/title" />!</p>
</body>
</html>This will greet a logged in user with his or her actual name.Such a template-using page is a subclass ofgrokcore.view.View:import grokcore.view
import zope.interface

class Hello(grokcore.view.View):
    grokcore.view.context(zope.interface.Interface)To associate the template with the view, we have to put it in a
certain place.  Let’s say theHelloview class from above was in
anapp.pymodule.  Then we create anapp_templatesdirectory
next to it and place the template file in there (the name of this
directory can be customized with thetemplatedirdirective, see
below).  The file name can be anything as long as the extension is.pt.  However, we can again make use of a convention here.  If we
name the template like the class (except in lower case characters),
then the template and the class are associated automatically.  If not,
we would have to use thetemplatedirective on the view class to
spell out the name of the template file explicitly.To cut a long story short, if we named itapp_templates/hello.pt,
it would be found automatically.Static resourcesBrowser pages often need additional static resources like CSS and JavaScript
files. These can be conveniently placed into a directory calledstaticin
the package that contains the view code. When this directory exists it will
automatically be registered as a resource directory. It then is available as
thestaticvariable in all views of this package and you can refer to files
inside this directory like so:<img src="hello.png" tal:attributes="src static/hello.png" />DirectoryResourceIn addition to the very convenient “static resources”, one can use more
explicitly configured and flexible DirectoryResource components.
DirectoryResource component allow for differentiating resources based on layers
and names and provide a way to register resources in one package and make use
of these resources in another package’s views:class FooResource(grokcore.view.DirectoryResource):
    grokcore.view.path('foo')Or with an explicit name:class BarResource(grokcore.view.DirectoryResource):
    grokcore.view.name('bar')
    grokcore.view.path('bar')Registered for a layer:class BazResource(grokcore.view.DirectoryResource):
    grokcore.view.layer(ISomeLayer)
    grokcore.view.path('baz/qux')Layers and skinsTo define a browser layer, simply extend theIBrowserRequestinterface:class IGreenLayer(grokcore.view.IBrowserRequest):
    passIf you then wanted to define a skin, simply inherit from all the layer
interfaces that should be in the skin and use theskin()directive
to give the layer a name:class IGreenSkin(IGreenLayer, grokcore.view.IDefaultBrowserLayer):
    grokcore.view.skin('Green')To place a view on a layer, simply use thelayerdirective:class Hello(grokcore.view.View):
    grokcore.view.context(zope.interface.Interface)
    grokcore.view.layer(IGreenLayer)

    ...API overviewBase classesViewBase class for browser pages.  Use thecontextdirective to
specify the view’s context.  Use thenamedirective to set the
view’s name; if not used, the view’s name will be the class’s name
in lower case characters.  You may also use thetemplatedirective to specify the name of the template file that should be
associated with the view as well as thelayerdirective to
specify which layer it should be on if not the default layer.
Implement therendermethod to forgo looking up a template
and show the result of calling the render method instead.View APIgrokcore.view.Viewis a regular Zope browser page, so it behaves
exactly like a regular browser page from the outside.  It provides a
bit more to the developer using it as a base class, though:contextThe view’s context object.  This can be discriminated by using thecontextdirective on the view class.requestThe request object, typically providesIBrowserRequest.responseThe response object, typically providesIHTTPResponse.staticDirectory resource representing the package’sstaticdirectory or None
if no such directory was found during grokking.redirect(url)Redirect to the given URL.url(obj=None, name=None, data=None)Constructs a URL:If no arguments are given, the URL to the view itself is
constructed.If only theobjargument is given, the URL to that object is
constructed.If bothobjandnamearguments are supplied, construct
the URL to the object and appendname(presumably the name
of a view).Optionally,datacan be a dictionary whose contents is added to
the URL as a query string.Method for developers to implement:update(**kw)This method will be called before the view’s associated template
is rendered.  If you therefore want to pre-compuate values for the
template, implement this method.  You can save the values onself(the view object) and later access them through theviewvariable from the template.  The method can take
arbitrary keyword parameters which are filled from request values.render(**kw)Return either an encoded 8-bit string or a unicode string.  The method can
take arbitrary keyword parameters which are filled from request values.
If not implemented, a template is looked up in the template dir instead.Directivestemplatedir(dirname)Module-level directive that tells the template machinery which
directory to look in for templates that should associated with
views in a particular module.  If not used, it defaults to<module_name>_templates.template(filename_wo_ext)Class-level directive that specifies the name a template file
that’s associated with a view class,withoutthe file extension.
If not used, it defaults to the class’s name in lower case
characters.layer(layer_interface)Class-level directive that defines which layer the view is
registered on.  If not used, it defaults to theIDefaultBrowserLayer.skin(skin_name)Directive used on a layer interface to register it as skin using a
human-readable name (skin_name).path(relative_or_absolute_path)Directove used in a DirectoryResource registration to point to a non-
package directory(hierarchy) containing resources like images, css files,
etc.Otherurl(request, obj, name=None, data=None)Generate the URL to an object, with an optional view name
attached.  Thedataargument can be a dictionary whose
contents is converted into the a query string that’s appended to
the URL.PageTemplate(template_code)Create an inline PageTemplate object.PageTemplateFile(filename)Create a PageTemplate object from a file.IBrowserRequestBrowser request interface fromzope.publisher.IDefaultBrowserLayerDefault layer for browser components fromzope.publisher.In addition, thegrokcore.viewpackage exposes thegrokcore.componentandgrokcore.securityAPIs.Changes4.0 (2023-02-16)Add support for Python 3.11.Drop support for Python 2.7, 3.5, 3.6.3.2 (2022-02-16)Add support for Python 3.7, 3.8, 3.9, and 3.10.Drop support for Python 3.4.Update the tests tomartian >= 1.5, thus requiring at least that version.3.1 (2018-06-13)Added AfterTraversalEvent which is fired after all traversal is done.3.0.3 (2018-01-12)Rearrange tests such that Travis CI can pick up all functional tests too.3.0.2 (2018-01-05)Additional test fixes.3.0.1 (2018-01-05)Additional test fixes.3.0 (2018-01-03)In the template directory grokker, ignore directories and files
without extensions.Drop support of Python 2.6.Claim support for Python 3.4, 3.5, and 3.6.2.10.2 (2016-02-02)Update tests.2.10.1 (2014-07-29)Fix broken MANIFEST.in2.10 (2014-07-29)Add an helperrender_providerto look up and render a given
content provider.2.9 (2014-05-15)Make possible to disable the template warning with the help of theGROK_DISABLE_TEMPLATE_WARNINGenvironment variable.Theskinoption ofgrokcore.view.util.urlnow accepts
strings that will be used as skin name as possible alternative to a
skin interface.Theskindirective can now be used on interfaces that inherits
only fromIRequestinstead ofIBrowserRequest.2.8 (2012-12-11)Add askin=[skincomponent]argument to thegrokcore.view.util.url()function andgrokcore.view.components.View.urlmethod. This allows for
computing URLs on a specific skin. Note that it is not verified whether
the computed URL actually exist on the specified skin.2.7 (2012-05-01)Use the component registration api in grokcore.component.Improve error message when a templatedir() directive points to a non-
existent directory. (fix launchpad issue 680528).Improve error message when a template is required for a component
but cannot be found (Fix Launchpad issue #225855, #242698).Fix how the static resource are found. Instead of using as name the
package name where the component is defined, using as name the
package where the template for the component is defined, or the base
component. This is done by setting an attribute__static_name__on the component that specify which resource directory should be
used. This fix missing resources when you extend the component and
don’t redefined the template.2.6.1 (2011-06-28)Fix bug where zope.browserpage was not correctly declared as a dependency.2.6 (2011-06-28)Add the ContentProvider component.2.5 (2011-04-04)Fix a test that relied on older zope.testbrowser behaviour.2.4 (2011-03-01)grok.View component can optionally use thegrok.providesdirective,
specifying an interface that the component provides (instead of the
zope.interface.Interface that views by default provide).Add a new ZCML directive,ignoreTemplatesthat let you configure which
template filename pattern should be ignored by the template registry. The
pattern attribute of the directive accepts regular expresssion that will be
matched against the (template) file extension.Use the zope configuration action ordering feature to have templates
registered for all packages and modules, before trying to associate the
templates. Checking for unassociated templates is done very very late in the
configuration action order.Inherited grok.template() information is looked up against the module of
the view class that uses the grok.template() directive. This allows for
subclassing view components that use the grok.template() directive from other
packages.2.3 (2011-01-04)Removed the static directory grokker in order to make way for using
fanstatic.2.2 (2010-12-16)Factor out a base template grokker that associate templates for
viewish components.Merge support for a global template registry that removes
unnecessary warnings about unassociated templates in “shared”
template directories.2.1 (2010-11-03)Use an update martian and grokcore.component.The custom zope publication has now moved from the grok package to
grokcore.view. The registration of the publication is optional, and is used
by grok and the grokcore.json package.The util functionmake_checkerhas been moved from thegrokpackage togrokcore.view.2.0 (2010-11-01)Theviewdirective has been moved fromgrokcore.viewlettogrokcore.view.TheIGrokSecurityViewhas been moved fromgroktogrokcore.view.Fix the url() function to behave properly while passed an empty data dict.Fix the url() method to accept the “status” and “trusted” arguments, passed
on to the redirect method on the response object.grokcore.viewno longer depends onzope.app.testingand
related packages. Instead we now usezope.app.wsgi.testlayerto
run functional tests.Made package comply to zope.org repository policy.Fixed launchpad bug #395061 : removed the default_fallback_to_name
function. It can be imported fromgrokcore.securityif needed.grokcore.viewno longer depends onzope.app.zcmlfiles. We
removed all the extra dependencies and fixed one test that usedzope.app.rotterdamandzope.app.basicskin.Back-ported the changes of the 1.13 branch related to the directory
resource registration, using the latest ztk packages.Factor out generally useful methods and properties for view-ish
components into components.ViewSupport mixin.Works with new Martian (0.13) and grokcore.component 2.1.Test fix: support windows paths.Warnings are now emitted as log messages with levellogging.WARNINGto a logger namedgrokcore.viewwith levellogging.ERROR.That means that by default no warnings are emitted anymore (while
errors will still appear).To get the warnings back, reduce the level of loggergrokcore.viewtologging.WARNINGor lower. This can be done in
Python or via a logging conf file, for instance in the .ini files of
regular grokprojects. See the Python standard libloggingmodule
for details.1.12.1 (2009-09-17)A compatibility fix to supportgrokcore.viewlet.1.12 (2009-09-17)Use 1.0b1 versions.cfg in Grok’s release info instead of a local
copy; a local copy for all grokcore packages is just too hard to
maintain.Revert the splitting CodeView/View. The original reasons for the
split have been obsoleted by the recent martain developments
regarding inheritted module level directives. At the same time the
split up components proved cumbersome to use and a too big a change
between the 1.0a and 1.0b releases of Grok.View components will now again behave like it did up until the latest alpha
release of Grok.CodeViewis still available as a backwards compatibility alias
forView. Please update all references toCodeViewtoView.Fix the template registry and grokker for views to let View and
other components using View as base class to be associated with a
template directly by setting it as ‘template’ attribute on the view
class. Example:class MyView(grokcore.view.View):

    template = grokcore.view.PageTemplate('<p>hello</p>')This isn’t exactlyofficiallysupported but enough people depend
on it and have documented it so that we don’t want to just break it.1.11 (2009-09-15)The response attribute needs to be available in CodeView as well.1.10 (2009-09-14)Up the version requirement for grokcore.security to 1.2.Bring versions.cfg in line with current grok versions.cfg.1.9 (2009-07-04)Fix needed for grokcore.formlib: allow a base_method’ed render() on view.
This allows grokcore.formlib to have a render() in addition to a template.Reverted change to checkTemplates: for some formlib edge cases it detects
the right templates again.1.8 (2009-07-04)Add validator to templatedir directive to disallow path separator.Splitted CodeView out of View.  View only uses templates, CodeView only uses
a render() method.  So views that have a render method must subclass from
CodeView instead of View (that should be the only change needed).Add grok.View permissions to functional tests (requires grokcore.security 1.1)1.7 (2009-05-19)Revert dependency from zope.container back to zope.app.container.1.6 (2009-04-28)Simplify the DirectoryResource and DirectoryResourceFactory
implementations by making better use of the hook points provided by
zope.app.publisher.browser.directoryresource.1.5 (2009-04-10)Don’t register a ‘static’ resource directory if the ‘static’ directory does
not exist.Make it possible to instantiate an ungrokked view by being slightly more
defensive in __init__. This makes it easier to write unit tests.1.4 (2009-04-08)Page template reloading now also works for macros. Fixeshttps://bugs.launchpad.net/grok/+bug/162261.Use zope.container instead of zope.app.container.Ignore ‘<tpl>.cache’ files when looking up template files in a
template dir. Fix bughttps://bugs.launchpad.net/grok/+bug/3327471.3 (2009-01-28)Adapt tests to work also from eggs not only source checkouts by
avoidingsrcin directory comparisons.Fix the factory for subdirectories of the DirectoryResource implementation
by using hooks in zope.app.publisher.browser.directoryresource.Update APIs interfaces to include the newpathdirective and
newDirectoryResourcecomponent.1.2 (2008-10-16)Expose theDirectoryResourceclass as a component for registering
directories as resources. This is accompanied by thepathdirective that
is used to point to the directory holding resources by way of an relative (to
the module) or absolute path.DirectoryResourcecomponents can be
differentiated by name and layer.1.1 (2008-09-22)meta.pymodule containing the grokkers has been split in a
package with separate modules for the view, template, skin and
static resources grokkers. This allows applications to use only
grokkers they need (and maybe redefine others).1.0 (2006-08-07)Createdgrokcore.viewin July 2008 by factoring security-related
components, grokkers and directives out of Grok.