PHP简单模板引擎/函数

4

我需要创建一个简单的模板引擎;不能使用Twig或Smarty等,因为项目中的设计师需要能够轻松地将她的HTML代码复制/粘贴到模板中,无需任何配置。它必须是非常易用的。

因此,我创建了一个允许她这样做的东西,即在{{ CONTENT }}{{ !CONTENT }}标记之间放置内容。

我的唯一问题是,我想确保如果她在标记中使用多个空格或没有空格,它也不会出现问题,例如{{ CONTENT }}{{CONTENT}}

下面的代码可以实现这一点,但我担心可能有点过于复杂。是否有人知道如何简化这个函数?

function defineContent($tag, $string) {

    $offset = strlen($tag) + 6;

    // add a space to our tags if none exist
    $string = str_replace('{{'.$tag, '{{ '.$tag, $string);
    $string = str_replace($tag.'}}', $tag.' }}', $string);

    // strip consecutive spaces
    $string = preg_replace('/\s+/', ' ', $string);

    // now that extra spaces have been stripped, we're left with this
    // {{ CONTENT }} My content goes here {{ !CONTENT }}

    // remove the template tags
    $return = substr($string, strpos($string, '{{ '.$tag.' }}') + $offset);
    $return = substr($return, 0, strpos($return, '{{ !'.$tag.' }}'));

    return $return;
}

// here's the string
$string  = '{{     CONTENT  }} My content   goes here  {{ !CONTENT   }}';

// run it through the function
$content = defineContent('CONTENT', $string);

echo $content;

// gives us this...
My content goes here

编辑

最终创建了一个仓库,供任何有兴趣的人使用。

https://github.com/timgavin/tinyTemplate


我认为她可以简单地学习忽略掉一些东西(例如循环、条件等),并且你可以使用替代语法来使事情更容易:http://php.net/manual/en/control-structures.alternative-syntax.php。在我看来,你根本不需要这个...但这只是我的看法... :) - sinisake
@不用在意,这不仅涉及到“CONTENT”标签,她还需要访问页面上的许多部分和标签,如果我在其中加入太多PHP代码,她会很生气的。 :) - timgavin
2个回答

10
我建议您查看将变量提取到模板范围中的方法。这比替换方法更容易维护,开销更小,并且对于设计师来说更容易使用。在其基本形式中,它只是PHP变量和短标签。
这取决于您生成的哪一侧,例如表格及其行(或完整的内容块)- 它可能只是<?=$table?> ;) 对于设计师来说工作量较小,对您来说则相反。或者只需提供一些渲染示例和帮助程序,因为复制/粘贴示例应始终有效,即使对于未经训练的设计师也是如此。 模板 模板只是混合了HTML和<?=$variable?>的代码 - 简洁明了。 src/Templates/Article.php
<html>
 <body>
 <h1><?=$title?></h1>
 <div><?=$content?></div>
 </body>
</html>

Usage

src/Controller/Article.php

...

// initalize
$view = new View;

// assign
$view->data['title'] = 'The title';
$view->data['content'] = 'The body';

// render
$view->render(dirname(__DIR__) . '/Templates/Article.php');

视图/模板渲染器

这里的核心功能是render()。 模板文件被包含,并且变量提取发生在闭包内,以避免任何变量冲突/作用域问题。

src / View.php

class View
{
    /**
     * Set data from controller: $view->data['variable'] = 'value';
     * @var array
     */
    public $data = [];

    /**
     * @var sting Path to template file.
     */ 
    function render($template)
    {
        if (!is_file($template)) {
            throw new \RuntimeException('Template not found: ' . $template);
        }

        // define a closure with a scope for the variable extraction
        $result = function($file, array $data = array()) {
            ob_start();
            extract($data, EXTR_SKIP);
            try {
                include $file;
            } catch (\Exception $e) {
                ob_end_clean();
                throw $e;
            }
            return ob_get_clean();
        };

        // call the closure
        echo $result($template, $this->data);
    }
}

0

具体回答你的问题:

我的唯一问题是,我想确保如果她在标签中使用多个空格或没有空格,它不会出错

下面的代码可以实现这一点,但我担心它可能过于复杂。有人知道简化此函数的方法吗?

... 你的函数中唯一“慢”的部分是 preg_replace。使用 trim 代替,速度会稍微快一些。否则,不用担心。没有魔法 PHP 命令可以做到你想要的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接