我知道這篇文章已經超過一歲了,但我有一個解決方案。 CI模板解析器的輕量級是我最近需要的一個項目,但我也遇到了同一個模板中多次出現相同變量對的問題。我依靠str_replace()替換字符串數組的能力解決了這個問題。將以下代碼投入到./application/libraries/MY_Parser.php中:
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Overrides the CI Template Parser to allow for multiple occurrences of the
* same variable pair
*
*/
class MY_Parser extends CI_Parser {
/**
* Parse a tag pair
*
* Parses tag pairs: {some_tag} string... {/some_tag}
*
* @access private
* @param string
* @param array
* @param string
* @return string
*/
function _parse_pair($variable, $data, $string)
{
if (FALSE === ($match = $this->_match_pair($string, $variable)))
{
return $string;
}
$str = array();
foreach ($match['0'] as $mkey => $mval)
{
$str[$mkey] = '';
foreach ($data as $row)
{
$temp = $match['1'][$mkey];
foreach ($row as $key => $val)
{
if (! is_array($val))
{
$temp = $this->_parse_single($key, $val, $temp);
}
else
{
$temp = $this->_parse_pair($key, $val, $temp);
}
}
$str[$mkey] .= $temp;
}
}
return str_replace($match['0'], $str, $string);
}
// --------------------------------------------------------------------
/**
* Matches a variable pair
*
* @access private
* @param string
* @param string
* @return mixed
*/
function _match_pair($string, $variable)
{
if (! preg_match_all("|" . preg_quote($this->l_delim) . $variable . preg_quote($this->r_delim) . "(.+?)". preg_quote($this->l_delim) . '/' . $variable . preg_quote($this->r_delim) . "|s", $string, $match))
{
return FALSE;
}
return $match;
}
}
// END Parser Class
/* End of file MY_Parser.php */
/* Location: ./application/libraries/MY_Parser.php */
*您正在使用哪個*模板分析器類?你期望它應該如何工作,你爲什麼期望如此? – hakre
內置模板解析器類。我期望我能夠多次遍歷列表{list} {/ list},並且因爲那是多麼聰明。 – user781439