[eluser]vendiddy[/eluser]
Hi all! This is a helper function I sometimes use to render html elements when I need to generate them dynamically.
Code:
function render_html($element)
{
if (is_string($element)) return $element;
$attributes = array();
$appended_elements = array();
foreach ($element as $property => $value) {
if (is_int($property)) {
$appended_elements[] = render_html($value);
} elseif ($property{0} != '#') { //Attributes don't start with '#'
$attributes[] = "$property = \"$value\"";
}
}
if (isset($element['#tag'])) {
return sprintf('<%s%s%s>%s</%s>%s', $element['#tag'],
count($attributes) > 0 ? ' ' : '',
implode('', $attributes),
empty($element['#inner_html']) ? '' : render_html($element['#inner_html']),
$element['#tag'],
implode('', $appended_elements));
} else {
return implode('', $appended_elements);
}
}
Here is a function you could stick in a controller to test it:
Code:
function test_render_html()
{
$this->load->helper('html');
$table = array('#tag' => 'table');
$table['border'] = '1';
$header = array(
'#tag' => 'tr',
'#inner_html' => '<th>A</th><th>B</th><th>C</th>',
);
$table['#inner_html'][] = $header;
for ($i = 1; $i <= 5; $i++) {
$td = array('#tag' => 'td', '#inner_html' => "Row $i");
$table['#inner_html'][] = array(
'#tag' => 'tr',
'#inner_html' => array($td, $td, $td)
);
}
echo render_html($table);
echo '<pre>' . print_r($table, TRUE) . '</pre>';
}
Any feedback is appreciated.