You are here: Home / Documentation / How To's / Simple trick to make views within views.

Simple trick to make views within views.

by hietpd31 — published Apr 13, 2011 01:25 PM, last modified Aug 16, 2016 10:50 AM
How to render a View within another View. Sub Views and Generic Views
This is a simple trick to really break apart your templates into reusable pieces without macros.

 

Your standard page template: my_template.pt

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
      lang="en"
      metal:use-macro="here/main_template/macros/master"
      i18n:domain="plone">
<body>

  <h1>What will this do?</h1>
  <tal:insert context="structure context/my_sub_view" />

</body>
</html>

Your reusable sub view:  my_sub_view.pt

<div>This is a snippet of html that can be reused in many templates</div>
<div tal:content="context/Title">Note the context of the object was passed in</div>

And your done, this is a very easy way to make snippets of template code reusable.

 

With BrowserViews

If you are using BrowserViews with your templates make sure your subviews for="something" is targeting the correct interfaces or to * for all.

<browser:page
    for="*"
    name="my_sub_view"
    template="templates/my_sub_view.pt"
    class=".subviews.MySubView"
    permission="zope2.View"
/>

 

 

 I want to pass data from one view to another???

 Well you are in luck!  You will need to add this BrowserView class though.

class SubViewHook(BrowserView):
    """ This hook class allows hand off of data through subviews. """
    def __call__(self, **kwargs):
        for key in kwargs:
            setattr(self,key, kwargs[key])
        return super(SubViewHook, self).__call__()

Then add it to your conifgure.zmcl

<browser:page
	for="*"
	name="your_subview_with_data"
	class=".view_classes.SubViewHook"
	template="templates/your_subview_with_data.pt"
	permission="zope2.View"
/>

Then in your_subview_with_data.pt

<div tal:content="view/someCustomData"></div>

One last step!  You'll need to pass the data in my_template.pt.  Notice the difference from the example above.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
      lang="en"
      metal:use-macro="here/main_template/macros/master"
      i18n:domain="plone">
<body>

  <h1>I just passed data through!</h1>
  <tal:insert content="structure python: context.restrictedTraverse('your_subview_with_data')(someCustomData=context.Title)" />

</body>
</html>

This trick is best used if you are doing a tal:repeat.  Sometimes you just need to pass through a small amount data which was parsed during the loop.

For Example: You are in a folder context and you need to loop through a bunch of link objects which all have Subjects (keywords) assigned.  Each keyword might need to render differently.  So you setup a few subviews and pass the link data through.  The context of subview is still the folder, but you now have the context of the link as well via this subview hook.

 

 

 

 

 

 

 

Navigation