Randall's Blog

a place for my thoughts

Using XPath Select with Genshi's Match Template

written by randall, on Oct 4, 2009 10:51:00 PM.

This entry details how I used Genshi's match templates for a two column layout with each column receiving template data. The key is XPath support and I found this page to be very helpful. Also, the genshi tutorial.

The thing to pay attention to is the syntax for "select". Both columns in the layout are selected using the XPath syntax //tag[@attribute='id_name']. So within the body that has been matched, the div with id="content" can be selected using this syntax:

    ${select("//div[@id='content']")}

The Layout Template (layout_template.html)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:py="http://genshi.edgewall.org/" py:strip="">
<py:match path="head" once="true">
<head py:attrs="select('@*')">
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title py:with="title = list(select('title/text()'))">
    My Site - <py:if test="title">${title}</py:if>
</title>
</head>
</py:match>
<py:match path="body" once="true">
<body py:attrs="select('@*')">
	<!-- header stuff goes here -->
	<div id="page">
		<div id="content" py:strip="">
            ${select("//div[@id='content']")}
		</div>
		<!-- end #content -->

		<div id="sidebar" py:strip="">
            ${select("//div[@id='sidebar']")}
		</div>
		<!-- end #sidebar -->
		<div style="clear: both;">&nbsp;</div>
	</div>
	<!-- end #page -->
	<!-- footer stuff goes here -->
</body>
</py:match>
</html>

The Index Template (index_template.html)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:xi="http://www.w3.org/2001/XInclude"
      xmlns:py="http://genshi.edgewall.org/"
>
<xi:include href="layout_template.html" />
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Index Page</title>
</head>
<body>
    <div id="page">
        <div id="content">
            <p>your content</p>
	</div>
	<!-- end #content -->
        <div id="sidebar">
            <p>sidebar stuff</p>
	</div>
	<!-- end #sidebar -->
    </div>
    <!-- end #page -->
</body>
</html>

Comments

Leave a Reply