Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created July 1, 2011 12:06
Show Gist options
  • Save vaclavbohac/1058410 to your computer and use it in GitHub Desktop.
Save vaclavbohac/1058410 to your computer and use it in GitHub Desktop.
Latte macro for creating table from Nette\Database\Selection easily
<?php
/**
* Latte macros.
*
* @copyright Copyright (c) 2011 Vaclav Bohac
* @package Macros
*/
use Nette\Latte;
/**
* Macros helping with creating tables filled
* with Nette\Database data.
*
* @author Vaclav Bohac
* @package Macros
*/
class TableMacros extends Latte\Macros\MacroSet
{
public static function install(Latte\Parser $parser)
{
$me = new static($parser);
$me->addMacro("table", '?> <table><tr>
<?php $_selection = %node.word; $_columns = %node.array; foreach (array_keys($_columns) as $_heading) : ?>
<th><?php echo %escape($_heading) ?></th>
<?php endforeach ?>
</tr>
<?php foreach ($_selection as $_row) : ?>
<tr>
<?php foreach ($_columns as $_column) : $_format = False ?>
<td>
<?php
if (is_string($_column) && ($_pos = strpos($_column, ":")) !== False) {
$_format = substr($_column, $_pos + 1);
$_column = substr($_column, 0, $_pos);
}
if (($_isArray = is_array($_column)) || strpos($_column, ".") !== False) {
$_tmp = $_row;
foreach ($_isArray ? $_column : explode(".", $_column) as $_key => $_prop) {
if ($_key === "format") {
$_format = $_prop;
} else {
$_tmp = $_tmp->{$_prop};
}
}
$_result = $_tmp;
} else {
$_result = $_row->{$_column};
}
if ($_format) {
$_result = Nette\DateTime::from($_result)
->format($_format);
}
echo %escape($_result);
?>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table> <?php');
}
}
{block #content}
<h1>Seznam uživatelů</h1>
{table $users Jméno => firstname, Příjmení => lastname, Role => "roles.name", Vytvořeno => "created:d.m.Y"}
{* Results in ...
<table>
<tr>
<th>Jméno</th>
<th>Příjmení</th>
<th>Role</th>
<th>Vytvořeno</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>Admin</td>
<td>1.1.1970</td>
</tr>
<tr>
<td>Lorem</td>
<!-- ... -->
</tr>
</table>
*}
{/block}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment