2016-11-08 60 views
0

所以我爲我的公司正在開發的一個項目做了一個基本的模板系統。目前,我可以加載模板並將其打印出來,並使用我們開發的標籤通過在主模板中調用<template::>template_name<::/template>來調用另一個模板中的模板。只要我只打一個模板,這個工作就很棒。在模板標籤第一次出現之後,系統停止並且不繼續從數據庫中讀取其餘的字符串以獲得可能的其他模板標籤。替換一個單獨的作品,我該如何替換每一個標籤的發生?

如果我在腳本中多次調用SAME模板,它將渲染正確,但是如果我調用NEW模板,它將被系統忽略並作爲普通文本打印。

這是我目前的函數調用標籤和替換它們:

$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循環,並計數,但不知道正確的語法來做到這一點,我一直盯着這整天現在哈哈。提前致謝!

+0

嘗試使用'preg_replace_callback()'。它將替換正則表達式的所有匹配項,並且可以提供一個回調函數,該函數根據模板名稱查找替換項。 – Barmar

回答

1

您可以使用一個循環,不斷更換,直到字符串中沒有模板。

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

你並不需要使用while()環周圍mysql_fetch_array(),因爲查詢限制爲1行。

順便說一句,你應該停止使用mysql_*函數。轉換爲mysqliPDO,並使用準備好的查詢。

+0

非常感謝。這完全解決了這個問題。我使用'mysql_ *'函數是因爲向後兼容性,開發服務器沒有在php或mysql上運行非常新的版本,所以我們將考慮切換。謝謝 – Kaboom

+0

mysqli與PHP 5.0.7及更新版本一起使用。 PDO帶有PHP 5.1和更新的版本。向後兼容性不應該成爲問題。 – Barmar