Edgewall Software

Genshi Recipes: Replacing py:layout with Includes

As noted in GenshiVsKid, Genshi does not support the py:layout directive for template reuse.

This page shows how the example from the Kid language specification translates to a functionally equivalent setup in Genshi.

Assume the following layout template, stored as layout.html:

<html xmlns:py="http://genshi.edgewall.org/" py:strip="">

  <head>
    <title>App Name - ${page_title()}</title>

    <link href="layout.css" type="text/css" rel="stylesheet" />
    ${page_specific_css()}
  </head>

  <body>
    <h1>Now viewing: ${page_title()} of App Name</h1>

    <content>Default content</content>

    <div class="footer">Page Footer Text</div>
  </body>

</html>

And the following page-specific template, stored as page.html:

<html xmlns:py="http://genshi.edgewall.org/"
      xmlns:xi="http://www.w3.org/2001/XInclude">

  <py:def function="page_title">Content Page 1 of 10</py:def>

  <link py:def="page_specific_css"
    href="page.css" type="text/css" rel="stylesheet" />

  <div py:match="content">
    <ul>
      <li>Content Item 1</li>
      <li>Content Item 2</li>
      <li>Content Item 3</li>
    </ul>
  </div>

 <xi:include href="layout.html" />

</html>

The “trick” here is that the base template is included at the bottom of the page template. This results in the template functions page_title() and page_specific_css() being available to the layout template, and the match template defined in the page template being applied to the layout template.

When rendered, the following output would be generated:

<html>
  <head>
    <title>App Name - Content Page 1 of 10</title>
    <link href="layout.css" type="text/css" rel="stylesheet">
    <link href="page.css" type="text/css" rel="stylesheet">
  </head>
  <body>
    <h1>Now viewing: Content Page 1 of 10 of App Name</h1>
    <div>
      <ul>
        <li>Content Item 1</li>
        <li>Content Item 2</li>
        <li>Content Item 3</li>
      </ul>
    </div>
    <div class="footer">Page Footer Text</div>
  </body>
</html>

See also: GenshiRecipes/PyExtendsEquivalent, GenshiRecipes, GenshiVsKid, Genshi XML Template Language

Last modified 17 years ago Last modified on Jul 4, 2007, 5:02:02 PM