我遇到了这个有趣的模板工具,作者称之为 hQuery,它是一个“不显眼的服务器端脚本”。[更多信息在这里 - https://github.com/choonkeat/hquery ]。它是在 Ruby 中为 RoR 平台构建的。
我想知道其他平台(PHP、Python、Java)是否有类似的东西
PS:我知道模板引擎,如 smarty 和 twig。我正在寻找更接近 hQuery 的东西。
我遇到了这个有趣的模板工具,作者称之为 hQuery,它是一个“不显眼的服务器端脚本”。[更多信息在这里 - https://github.com/choonkeat/hquery ]。它是在 Ruby 中为 RoR 平台构建的。
我想知道其他平台(PHP、Python、Java)是否有类似的东西
PS:我知道模板引擎,如 smarty 和 twig。我正在寻找更接近 hQuery 的东西。
不是我知道的,但我一直在做一些类似的概念,虽然更简单,在 PHP 中使用phpQyery和一些自定义的类似 html 的标记。
例如,这是一个简化的非标准 html 块:
<bodynode>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<div class="holder">
<article>
<header class="col_12f">
<component id="logo"></component>
<component id="address"></component>
<component id="languages"></component>
<component id="mainmenu"></component>
</header>
<section id="banner">
<component id="maingallery"></component>
<component id='sideMenu'></component>
</section>
<section class="col6 first" id="intro_title">
<h1 class="underlined"></h1>
<section class="col3 first" id="intro_col1"></section>
<section class="col3 last" id="intro_col2"></section>
</section>
<section class="col3" id="location"></section>
<section class="col3 last" id="services"></section>
</article>
<div class="clear"></div>
</div>
<component id="footer"></component>
</bodynode>
使用 phpQuery,它在服务器端与 XML 和 HTML Dom 节点一起工作,其方式与 jQuery 非常相似,我将所有标签映射到来自数据库的内容,使用它们的 ID 作为键。以及所有<component></component>
具有函数自定义输出的标签。所以 a 的存在<component id="logo"></component>
会导致调用一个名为 component_logo 的函数,使用:
function replaceComponents ($pqInput){
$pqDoc = phpQuery::newDocument($pqInput);
$comps = pq('component');
foreach ($comps as $comp){
$compFunc = 'component_'.pq($comp)->attr('id');
pq($comp)->replaceWith($compFunc($comp));
}
return $pqDoc;
}
和
function component_logo($comp){
$pqComp = phpQuery::newDocument(file_get_contents('Templates/Components/logo.component.html'));
$pqComp->find('a')->attr('href','/'.currentLanguage().'/')->attr('title','Website Title');
$pqComp->find('img')->attr('src','/Gfx/logo.png');
return $pqComp;
}
尽管它不是基于 MVC 模式并且使用直接的过程编程,但到目前为止,这种方法已经允许非常快速地开发中小型站点,同时保持良好的 DRY。
我不太喜欢使用其他模板引擎,真的是因为我发现它们对于我真正想做的任何事情都有点重量级(例如聪明)。
有一种思想会说:PHP 已经是一个模板引擎……为什么要在模板中构建模板?
我在一定程度上不同意这一点,我发现模板在从 PHP 代码中抽象 HTML 时非常有用。
下面是我使用的模板类中的一个编辑方法,它将解释实际制作自己是多么容易。
$params = array("<!--[CONTENT]-->" => "This is some content!");
$path = "htmltemplates/index.html";
$html = implode("",file($path));
foreach($params as $field => $value) {
$html = str_ireplace($field, $value, $html);
}
echo $html;
这方面还有很多内容,但这是核心代码。将文件读入数组,内爆,搜索 $params 数组并将 $field 替换为 $html 中的 $value。输出编辑后的 $html。
您的 index.html 文件将类似于:
<html>
<head>
<title>This is a template</title>
</head>
<body>
<div id="page-container">
<!--[CONTENT]-->
</div>
</body>
</html>
您的输出将是:
<div id="page-container">
This is some page content!
</div>
也许看看实现你自己的模板引擎!:)