Reputation: 32412
I'm trying to implement a "Flash Message" (a little message that'll show on the top on the "next" request, saying things like "record saved"), in a PHP site that has pretty messy code and uses Smarty.
The best I could come up with is:
My problem is with #3. The only way I could find of doing it was registering an output filter with Smarty:
function smarty_outputfilter_flashmessage($tpl_output, $smarty) {
if (isset($_SESSION['flash'])) {
$_SESSION['flash'] = "";
}
return $tpl_output;
}
$smarty->register_outputfilter("smarty_outputfilter_flashmessage");
The problem with that is that, if a template has sub-templates, that function gets called for each sub-template. Also, there are a number of places in the code that do
$variable = $smarty->fetch('something.tpl')
which also triggers my outputfilter.
When that happens, the output filter clears the session variable before the header template is rendered, and the message is lost.
Any ideas/suggestions on how to better do this?
Is there some kind of PHP built-in callback to execute a custom function when a request "ends"? (With that, I could add the clearing there, and have the output_filter simply set a variable to show whether something was rendered)
Ideally, something that gets called unless the code calls die()?
Or, of course, another completely different and better way to do this?
Thanks!
Daniel
Upvotes: 1
Views: 3228
Reputation: 287860
I haven't seriously used PHP or Smarty in ages, but instead of trying to guess when a template was rendered, can't you do a Smarty function that does something like:
function smarty_function_pop_flash_message($params, $smarty) {
$msg = "";
if (isset($_SESSION['flash'])) {
$msg = $_SESSION['flash'];
$_SESSION['flash'] = "";
}
return $msg;
}
And then in the template where you show this message:
{if isset($smarty.session.flash) && $smarty.session.flash != ''}
<div id="flash">{pop_flash_message}</div>
{/if}
Upvotes: 2
Reputation: 10351
When I have used Smarty in the past, and wanted to be able to show messages, I have used the following method.
Within the PHP Script which processes the action and then generates the message:
$_SESSION['message'][] = 'The Message Content!';
Within the PHP Script which processes the next request/page and invokes the Smarty Template:
$smarty->assign( 'messages' , $_SESSION['message'] );
unset( $_SESSION['messages'] );
Within the Smarty Template (normally a commonly reused one, like the Header section
{include file='messages.tpl'}
And then within the "messages.tpl" Smarty template
{if $messages}
<div id="messages">
<ul>
{foreach $messages as $m}
<li>{$m}</li>
{/foreach}
</ul>
</div>
{/if}
It is not perfect in that, should more than one page be loaded simultaneously, the message may appear in the wrong one (a rare case, but a possible one), but it has worked well for me in the past.
(NOTE: These are scratched-together codes samples, trust at your own risk.)
Upvotes: 0