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

时间:2016-02-02 10:17:02

标签: php

我正在使用Wolf CMS,但我希望更轻松地加入snippets

目前必须写一个包含一个片段:

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

在这里,'scripts'是片段的名称。

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

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

因为代码行总是相同的,只有代码段名称会更改。

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

提前致谢

1 个答案:

答案 0 :(得分:1)

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

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);