所以我为我的公司正在开发的一个项目做了一个基本的模板系统。目前,我能够加载模板并将其打印出来,并使用我们开发的标记通过在主模板中调用<template::>template_name<::/template>
来在另一个模板中调用模板。只要我只调用一个模板,这个工作就很棒。在第一次出现模板标记之后,系统停止并且不继续从数据库中读取字符串的其余部分以获取可能的其他模板标记。
如果我在脚本中多次调用同一个模板,它将正确呈现,但如果我调用一个新模板,它将被系统忽略并作为正常文本打印。
下面是我当前调用和替换标签的函数:
$inject_template = $this->get_template_name_between($template, "<template::>", "<::/template>");
if(!empty($inject_template)) {
$query_for_template = "SELECT * FROM ".$field." WHERE templateid = '".$inject_template."' LIMIT 1";
$injected_template_data = $wms->function->query($query_for_template);
while($returned = mysql_fetch_array($injected_template_data)) {
$type = $returned['templatetype'];
}
$template = str_replace('<template::>'.$inject_template.'<::/template>', $this->injectTemplate($inject_template, $type), $template);
}
public function injectTemplate($template_id, $template_number_type) {
return $this->extract_template($template_id, $template_number_type);
}
public function get_template_name_between($string, $start, $end) {
$ini = strpos($string, $start);
if($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
请记住,如果我调用一个标签,这是有效的,我只需要一种方法来强制函数用每个标签的正确模板替换所有标签。我想也许是一个for循环,计数,但不确定正确的语法,我已经盯着这个一整天了,哈哈。提前感谢!
你可以使用循环不断替换,直到字符串中没有模板为止。
while ($inject_template = $this->get_template_name_between($template, "<template::>", "<::/template>")) {
$query_for_template = "SELECT * FROM ".$field." WHERE templateid = '".$inject_template."' LIMIT 1";
$injected_template_data = $wms->function->query($query_for_template);
$returned = mysql_fetch_array($injected_template_data);
$type = $returned ? $returned['templatetype'] : '';
$template = str_replace('<template::>'.$inject_template.'<::/template>', $this->injectTemplate($inject_template, $type), $template);
}
您不需要在mysql_fetch_array()
周围使用while()
循环,因为查询仅限于1行。
顺便说一句,你应该停止使用mysql_*
函数。转换为mysqli
或PDO
,并使用准备好的查询