Reputation: 2966
I tried to show a login/logout link in my header based on the value in session. i tried some thing like this
<ul class="nav navbar-nav navbar-right text-uppercase">
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'site/contactus' ] ); ?>">Contact</a></li>
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'site/modules' ] ); ?>">FAQ</a></li>
<?php
$session = Yii::$app->session;
$user_id = $session->get('userid');//print_r($user_id);die();
if($user_id != null)
{?>
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'userdetails/logout' ] ); ?>">Logout</a></li>
<?php}
else
{?>
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'userdetails/login' ] ); ?>">Login</a></li>
<?php } ?>
</ul>
then both links didn't appeare in the header(login/logout). then after a lot of trying i came up with this code
<ul class="nav navbar-nav navbar-right text-uppercase">
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'site/contactus' ] ); ?>">Contact</a></li>
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'site/modules' ] ); ?>">FAQ</a></li>
<?php
$session = Yii::$app->session;
$user_id = $session->get('userid');//print_r($user_id);die();
if($user_id != null)
{
?>
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'userdetails/logout' ] ); ?>">Logout</a></li>
<?php
}
else
{
?>
<li><a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ 'userdetails/login' ] ); ?>">Login</a></li>
<?php
}
?>
</ul>
the code is actually same but i have added some spaces between the curly brackets'{'. And it works as i intended. Is space an issue when we use html and yii2 code combined?
Upvotes: 0
Views: 55
Reputation: 25312
This has nothing to do with Yii, it is simply a php syntax problem (you should always have a space after <?php
)...
If you want to mix condition and html output, and have a better readability, you should use this :
<?php if ($user_id != null) : ?>
Output 1
<?php else : ?>
Output 2
<?php endif; ?>
Read more : http://php.net/manual/en/control-structures.alternative-syntax.php
Upvotes: 2
Reputation: 360762
There HAS to be a space after the opening <?php
tag, which means <?php}
is not valid:
without space:
$ cat z.php
<?php if(true) {?>
true
<?php} else {?> // note, no space after <?php
false
<?php }?>
$ php z.php
true
<?php} else {?>
false
with space:
$ cat y.php
<?php if(true) {?>
true
<?php } else {?>
false
<?php }?>
$ php y.php
true
Note the difference in output. This has nothign to do with Yii, and everything to do with your core PHP coding.
Upvotes: 1