1月
25
2008
分類:
最近更新:
2008-01-25
How do you write template? XSLT, PHP or RoR?
Using XSLT, PHP, or Ruby on Rails to transform XML documents into XHTML documents. 展示 XSLT, PHP 與 Ruby on Rails 的樣版撰寫風格。
在使用樣版引擎之前,我們需要先將資料自外觀中分離,因此 A Note of HTML Form and XForm 算是本文的前置文章。當我們將資料和外觀分離時,我們將更進一步考慮如何將外觀樣版化。
XML document
<bookstore>
<catalog>
<cd>
<title lang="eng">Harry Potter</title>
<artist>Potter</artist>
</cd>
<cd>
<title lang="eng">Learning XML</title>
<artist>LMX</artist>
</cd>
</catalog>
</bookstore>
XSLT style
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
使用 XSLT 的優點在於樣版語法和伺服端實作工具無關。當網頁設計人員在設計網頁樣版時,不必知道程式開發人員使用什麼開發工具。當程式開發人員在爭論用 JSP, ASP.Net, PHP 或 RoR 開發時,那些事跟網頁設計人員一點關係都沒有。
現實問題則在於支援 XSLT 的網頁設計工具少,會使用 XSLT 的網頁設計人員更少。
PHP style
<?php
// Select data from XML document.
$xml = new SimpleXMLElement($xmlSource);
$resultSet = $xml->xpath('catalog/cd');
// Select data from database by a pseudo object, $db.
$db->select_db('root'); # match = "/"
$resultSet = $db->query('select * from catalog_cd;'); # select="catalog/cd"
?>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<?php foreach ($resultSet as $value) : ?>
<tr>
<td><?=$value->title ?></td>
<td><?=$value->artist ?></td>
</tr>
<?php endforeach; ?>
</table>
PHP 是比 XSLT 更早出現的樣版設計技術。但它同時也具有程式開發工具的特性,所以經過多年的快速發展後,晚近者對 PHP 的印象是「網頁開發工具」,而忽視了它作為樣版設計工具的一面。
PHP is itself a powerful template system, many developers feel it is too powerful or complex for their template designers ...
Zend Framework
由於 PHP 的功能太過強大 (對樣版系統而言),前些年有人另外發展了一些樣版引擎,例如 Smarty 。但我個人的建議是: 該遺忘它們了。如果你的開發團體想要尋找一個與開發工具無關的樣版系統,現在是該認真考慮 XSLT 的時候。延伸閱讀:
Ruby on Rails style
<%
// Select data from XML document.
xml = REXML::Document.new(xmlSource).root;
%>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<% REXML::XPath.each(xml, 'catalog/cd') do |value| %>
<tr>
<td><%=value.elements['title'].text %></td>
<td><%=value.elements['artist'].text %></td>
</tr>
<% end %>
</table>
Reference
- XSL Transformations (XSLT) Version 1.0 - W3C Recommendation 16 November 1999
- XSL Transformations (XSLT) Version 2.0 - W3C Recommendation 23 January 2007
- PHP
- Ruby on Rails
樂多舊網址: http://blog.roodo.com/rocksaying/archives/5147001.html
樂多舊回應