0

说我有

$output = '';

我想在 double 中包含以下代码''

<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
    <a href="?route=common/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
    <a href="?route=subscribers/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>

我怎么能这样做呢?

4

2 回答 2

2

您可以使用输出缓冲,如下所示:

<?php ob_start();?>

<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
    <a href="?route=common/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
    <a href="?route=subscribers/home">
    <span class="menu-title">Home</span>
    </a>
</li>
<?php } ?>

<?php
    $output = ob_get_contents();
    ob_end_clean();  
?>

See In Action

使用这种启动缓冲区然后将结果分配给变量的方法非常方便,并且在一些 MVC 框架中使用。

简单的例子:

<?php
/* Assign an array of values that will be passed 
 * to the loader then extracted into local variables */
$data['logged']=true;
$output = loadContentView('top_nav', $data);


function loadContentView($view, $data=null){
    $path = SITE_ROOT.'/path/to/views/'.$view.'.php';

    if (file_exists($path) === false){
        return('<span style="color:red">Content view not found: '.$path.'</span>');
    }
    /* Extract $data passed to this function */
    if($data != null){
        extract($data);
    }
    ob_start();
    require($path);
    $return = ob_get_contents();
    ob_end_clean();
    return $return;
}
?>
于 2013-07-01T22:21:11.827 回答
1

我只是把我的代码改成了这个......更容易

感谢大家的帮助!

<?php

if (!$this->customer->isLogged()) {
$output = '<ul class="nav megamenu"><li class="home"><a href="?route=subscribers/home"><span class="menu-title">Home</span></a></li>';
}else{
$output = '<ul class="nav megamenu"><li class="home"><a href="?route=common/home"><span class="menu-title">Home</span></a></li>';
}

?>
于 2013-07-01T22:26:06.767 回答