包含代码片段的更简单方法


Easier way to include code snippets

我正在使用Wolf CMS,但我想更容易包含片段。

目前,必须编写此内容以包含一个片段:

<?php $this->includeSnippet('scripts'); ?>

在这里,"脚本"是代码段的名称。

我想做的是写一小段代码来解释这一点:

###scripts### as <?php $this->includeSnippet('scripts'); ?>

因为代码行总是相同的,只是代码段名称发生了变化。

这可能吗,还是我在这里问不可能的事情?

提前致谢

你可以为此定义一个函数:

function includeSnippetsFromList($snippets) {
    foreach ($snippets as $snippet) {
        $this->includeSnippet($snippet);
    }
}

。然后像这样称呼它:

$snippets = "snippet1,snippet2,scripts,specialSnippet,layoutSnippet";
// turn string to array of snippets and call function to include them:
includeSnippetsFromList(explode(",", $snippets));

当然,分离片段的方式可以不同。

如果你想把它们嵌入到一个长文本中并像###scripts###一样换行,那么你可以使用preg_match_all来提取它们:

function includeSnippetsFromText($text) {
    preg_match_all("/###(.*?)###/", $text, $matches);
    foreach ($matches[1] as $snippet) {
        $this->includeSnippet($snippet);
    }
}

像这样使用它:

$text = 
"This is a text
that has snippets, like
###snippet1###
###snippet2###
###scripts###
but also these:
###specialSnippet###
###layoutSnippet###
This is the end of this text.";
includeSnippetsFromText($text);