有没有像hQuery这样的服务器端脚本更容易模板化?

2024-06-10 09:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了这个有趣的模板工具,作者称之为hQuery,它是一个“不引人注目的服务器端脚本”。[此处提供更多信息-https://github.com/choonkeat/hquery]。它是在Ruby中为RoR平台构建的。你知道吗

我想知道其他平台(PHP、Python、Java)是否也有类似的功能


PS:我知道像smarty和twig这样的模板引擎。我在找更接近你的东西。你知道吗


Tags: 工具httpsgithub脚本com模板信息服务器端
2条回答

我不喜欢使用其他模板引擎太多,真的是因为我发现他们有点重量级的任何我真的想做(例如smarty)。你知道吗

有一个学派认为: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数组,并在$html中将$field替换为$value。输出编辑后的$html。你知道吗

你的索引.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>

也许可以考虑实现自己的模板引擎!:)

据我所知不是这样,但是我在概念上做了一些类似的事情,虽然简单得多,在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和htmldom节点,以一种非常类似于jQuery的方式,我用来自db的内容映射所有标记,使用它们的ID作为键。以及所有带有自定义函数输出的<component></component>标记。因此<component id="logo"></component>的存在会导致调用一个名为component\u 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模式,并且使用直接的过程编程,但是到目前为止,这种方法已经允许非常快速地开发中小型站点,同时使事情保持干净利落。你知道吗

相关问题 更多 >