Search code examples
phphtmlhtml-tablesmarty

Smarty inserts PHP function in <BODY> instead of inside <TD>


I have this simple PHP function in admin.php

function accountMenu()
{
    if (isset($_SESSION['user_id']))
        { ?>
      <a href="update_profile.php">Update My Profile</a><br>
      <a href="update_email.php">Update My E-mail Address</a><br>
      <a href="logout.php">Logout </a>
    <?php }
}

I assign a variable to this function in dashboard.php

//smarty paths here

include 'admin.php';

$accountMenu = accountMenu();

$smarty->assign('accountMenu', $accountMenu);
$smarty->display('dashboard.tpl');

And try to display this via dashboard.tpl

<body>
    <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
        <tr>
            <td width="160" valign="top">
            {$accountMenu}
            </td>
            <td width="732" valign="top">
                <h3>Dashboard</h3>
            </td>
        </tr>

        <tr>
            <td colspan="3">&nbsp;</td>
        </tr>
    </table>
</body>

What happens is that the accountMenu elements are shown immediately after <BODY> (and even before <TITLE>!) and not within the <TD>.

Any idea why this is happening?


Solution

  • Your function doesn't return anything - it simply outputs the HTML straight to the buffer, so when you call this:

    $accountMenu = accountMenu();
    

    It immediately prints it to the browser and $accountMenu remains NULL.

    Change it so that it returns the desired string, for example:

    function accountMenu()
    {
        if (isset($_SESSION['user_id'])) return '
          <a href="update_profile.php">Update My Profile</a><br>
          <a href="update_email.php">Update My E-mail Address</a><br>
          <a href="logout.php">Logout </a>
        ';
    }