How to create a dynamic template


#1

Dear masters,

I want to created a template named random.phtml to show some random results which can be included to other templates(index.phtml, subpage.phtml), the following code requires access to domain.com/random/ to get the results, how can i create the dynamic page without post/get queries?

at route.php

// random results
$app->get('/random/', function ($request, $response) {
$sth = $this->db->prepare("SELECT id,images FROM table ORDER BY RAND() LIMIT 10");
$sth->execute();
$todos = $sth->fetchAll();
return $this->renderer->render($response, 'random.phtml', array(
'results' => $todos,
));
});

random.phtml

<?php
if (!empty($results)) {
echo '<ul>';
foreach ($results as $result) {
echo '<li>'.$result['id'].' '.$result['images'].'</li>';
}
echo '</ul>';
}
?>

#2

Why don’t you include the code for the other pages you want the randomness to appear?
(Now you are kind of creating an extra hit on the webserver, which is ok, if your idea is that it is called via Ajax.)