在变量中包含PHP?
Say I have
$output = '';
and I want to include the following code within the 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 } ?>
How could I go about doing this?
说我有 p>
$ output =''; \ n code> pre>
我希望在双'' code>中包含以下代码。 p>
&lt; ul class =“nav megamenu”&gt;
&lt;?php if(!$ logged){?&gt;
&lt; li class =“home”&gt;
&lt; a href =“?route = common / home“&gt;
&lt; span class =”menu-title“&gt;主页&lt; / span&gt;
&lt; / a&gt;
&lt; / li&gt;
&lt;?php}?&gt;
&lt;? php if($ logged){?&gt;
&lt; li class =“home”&gt;
&lt; a href =“?route = subscribers / home”&gt;
&lt; span class =“menu-title” &gt;主页&lt; / span&gt;
&lt; / a&gt;
&lt; / li&gt;
&lt;?php}?&gt;
code> pre>
我怎么能去 关于这样做? p>
div>
You could use output buffering, something like this:
<?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();
?>
Using this method of starting a buffer and then assigning the result to a variable is very handy and is used in some MVC frameworks.
Simple example:
<?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;
}
?>
I just changed my code to this instead... much easier
Thanks everyone for all the help!
<?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>';
}
?>