I'm typing this on an iPad so forgive me if being concise is a bit rude. My question is:
Is it ever ok to have simple logic inside a view? For instance,
<HTML>
<!-- ... Stuff
-->
<?php if($this->session->userdata('authorized'): ?>
<p>You are authorized</p>
<?php else: ?>
<p>You are not authorized</p>
<?php endif; ?> // Question 1, is this the proper use of an endif:?
<!-- .. Stuff
->>
</HTML>
/* Starting to type the rest of message on my laptop. Big thank yous to the coders on
this site who made my pc login transfer my unsaved, half typed iPad post */
The above was just a leftover comment in the code that would have made the limited php use look ugly. I wanted to let it be seen though.
Anyways, on to question #2:
Is it even proper to use a simple conditional like this in a view?
Thanks for reading, and hello again.
In answer to the first question:
That is the proper use of an endif, all is valid and recommended way by codeigniter.
In terms of the second question, this method can be used in a view file; however I would recommend using it in the $data array passed to the page meaning it will be accessed as $authorised; I say this as it will make more sense to a front end designer.
Information on the $data array can be found here, just navigate to "Adding logic to the controller".
I hope this is of help to you.
I recommend you to use differents views in the controller for each case:
// In the controller
if($this->session->userdata('authorized')
$this->load->view('not_autorized.php');
else
$this->load->view('view.php');
So you get clean code an views.
Use the Language class to store your 'You are authorized' and 'You are not authorized' text. Do your session check in the controller, and pass the correct language value to the view in the data array.
Edit: Additional question from STONYFTW:
What approach should one take with a bit of more complex code, such as:?
<?php if(!$this->session->userdata('isLoggedIn')): ?>
<div id="login_form">
<?php echo form_open('login/validateCredentials'); ?>
<?php echo form_input('username', 'Username'); ?>
<?php echo form_password('password', 'Password'); ?>
<?php echo form_submit('submit', 'Log In'); ?>
<div id="login_form_link_container">
<?php echo anchor('login/register', 'Register')." ".anchor('login/recover','Forgot Pass?'); ?>
</div>
</div>
<?php endif; ?>
Related
We write PHP code inside the HTML code via <?php ... ?> tags. So normally it would not make sense to write HTML code inside PHP code that is already inside HTML code, if you can just exit the PHP for the lines you need. But what if you need the HTML code in the same line as you have the PHP code?
My example would go like this:
<div>
<?php ($bool) ? <script>...</script> : <script></script> ?>
</div>
Is this:
<div>
<?php if($bool): ?>
<script>...</script>
<?php else: ?>
<script>...</script>
<?php endif; ?>
</div>
the only way?
Note: instead of <script> you could have <h1>, <strong>, <title> or any other "one-liner".
Thank you in advance.
Sure, alternative syntax would be the way to go when you have multiple lines of HTML, as you already stated...
However, for one liners, you can shorten <?php echo '...' ?> with <?= '...' ?> and wrap your HTML within single or double quotes, depending if you are already using double quotes within your HTML syntax. You may also escape them if you like, but that'd be messy.
<div>
<?= ($bool) ? "<script>...</script>" : "<script></script>" ?>
</div>
In order to print any string into your html code from PHP snippets use echo function.
http://php.net/manual/en/function.echo.php
So you just need to add echo
<div>
<?php
if($bool) {
echo '<script>...</script>';
} else {
echo '<script>...</script>';
} ?>
Stumbled upon this and decided to answer my own question just to point other newbies in the right direction.
Important note: Nowadays I'm using Laravel Framework and if you don't know it, you should definitely get to know it (there are alternatives though).
But I started following MVC architecture strongly even before that. So even before Laravel's Blade templates, my views looked something like the following.
<html>
<body>
<?php if ($isUserAuthenticated) : ?>
<div>
<span>Welcome <?= $username ?>
</div>
<?php else : ?>
Login
<?php endif ?>
</body>
</html>
As you can see there is absolutely no data manipulation in the view.
I also tried my best not to store any HTML strings into variables, but sometimes it makes for less code, so I did something like the following.
$alert = match($errorCode) {
1 => <<<HTML
<div class="alert alert-danger">Big error</div>
HTML,
2 => <<<HTML
<div class="alert alert-warning">Small error</div>
HTML,
default => ""
};
That way I can keep syntax highlighting (in VSCode) for HTML.
Note: match expression is new in PHP8, but you could achieve the same before with a switch statement.
I'm struggling trying to understand cakephp's views, blocks and layouts.
I need everypage to show a left and right sidebar which content might change. At this moment I have the right sidebar defined in /pages/home.ctp but I'm guessing it would be better to extend that sidebar since it has to appear in everypage. Correct me if that thought is wrong.
Then, I have this view add.ctp for the 'usuarios' table, it practically shows the fields login and password. I want to show this view in the sidebar, but I'm really lost as how to do that.
Thanks in advance.
Lets make this thing easy. Like #patrick said, there is a lots of way.
Start with layout file. Rearrange your default.ctp layout like-
default.ctp layout
<div id="container">
<div id="header">
<?php echo $this->element('header');?>
</div>
<div id="left-sidebar">
<?php echo $this->element('left-sidebar');?>
</div>
<div id="content">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</div>
<div id="right-sidebar">
<?php echo $this->element('right-sidebar');?>
</div>
<div id="footer">
<?php echo $this->element('footer');?>
</div>
</div>
Now create elements ctp files as header.ctp, left-sidebar.ctp, right-sidebar.ctp and so on and place them to app/View/Elements.
Your left-sidebar.ctp file may looks like this...
left-sidebar.ctp
// to show login form //
if you just need to show on view.ctp place few logic here for login form.
//end login form//
show other sidebar contents
There are a couple ways to do it, depending on your Cake version. If you're using >=2.1 (which I assume you are since you asked about blocks), then you should try those to see if they work for your setup. The way I usually do things is that if all views for a controller need common markup then those view files would extend a base view within the Controller directory, e.g.
#/View/Posts/index.ctp
<?php
$this->extend('_skel'); //arbitrary filename, I use '_skel' since that makes sense
echo $this->Html->para(null, 'Hello');
#/View/Posts/_skel.ctp
<?php
echo $this->Html->div('sidebar', 'Sidebar for posts...');
echo $this->fetch('content'); // This gets all output from the Posts/index.ctp view
Then all your Posts views which extend _skel will have the sidebar automatically.
Your login module might make sense as an element - something that could be used anywhere in your views.
I have a copy of a PHP website and there are a lot of pages and a lot of code there. It uses conditional statements to determine what contents should be printed very much. Here's an example(there may be a lot of snippets like the one below):
<?php if($countryA): ?>
<div myattr="myvalue">
<?php elseif($countryB): ?>
<div myattr="myvalue">
<?php elseif($countryC): ?>
<div myattr="myvalue">
<?php elseif($countryD): ?>
<div myattr="myvalue">
<?php endif; ?>
Let's say, I don't care what it is in countryA,countryB and countryD, I only care if there is <div myattr="myvalue"> in countryC.
If I want know how many times <div myattr="myvalue">" will occur if $countryD is true, I need to perform a search among all the files in my website directory using keyword <div myattr="myvalue"> and check if there is <?php elseif($countryC): ?> in the context for every search result, which is really a huge burden...
Are there any ways to help me solve this problem efficiently? Do I need a PHP parser if I want to do this programmatically?
Either you need a parser or in other words , you have to save the format of your code or controls flow in a file or database and apply logic according to that saved data or flow.
I hope you get the sense.
This is my very first question at StackOverflow.
I was trying to post comment in the post Can a Joomla module "know" what position it's in?, but could find no way to do that so I have to post another question here. Any tips regarding how to do this properly is greatly apprieciated.
Anyway, here is my questions:
I tried the code mentioned in the above post but it seemed didn't work. I'm not only quite new to PHP, but also coding, so I'm not sure if it's me or the code. here's what I did to the module's default.php file:
1)to ensure I insert the code at the right place, I insert
<?php echo(print_r($module)); ?>
and it output 1 at the right position;
2)the position-name that I need to determine is "showcase-a", so I insert code
<?php if ($module->position == 'showcase-a'):?>test<?php endif;?>
to the above place, but this time it does't show anything;
3)then I tried this code:
<?php if ($module):?><span>test</span><?php endif; ?>
But still it does't display "test" at the position as I expected.
4)I tried
<?php if (1):?><span>test</span><?php endif; ?>
and the test "test" displays as good. So I didn't code the IF statement wrong.
Now I'm totally lost. Since print_r($module) outputs 1, $module must be positive, why PHP ignore test in 3)? This is just a side question for the sake of PHP learning. What I still need to solve is let the module determine which position itself is in.
Please help. Thank you!
I'm not sure about using it in the template (although it doesn't seem wrong altogether) but my modules oftentimes access the position like this:
$module->position
in the module (so mod_something.php) so try to put it there, if it's available just set a variable and it will be available in the view too.
If $module->position didn't work for you. $module->position may only work for joomla 1.7, 2.5 and + but i'm not sure. $module->position works in joomla 2.5.
Otherwise you need to make a module.php function
Check out the file
/templates/you-template/html/modules.php
For example you make your position the following in your template (for example index.php)
<jdoc:include type="modules" name="header" style="includeposition" />
inside of
/templates/you-template/html/modules.php
You make a function like this :
<?php
function modChrome_includeposition($module, &$params, &$attribs){
//Set a value to $module->position
$module->position='WHATEVER YOUWANT';
?>
<div class="moduletable <?php echo $params->get('moduleclass_sfx').' '.$module->name; ?>">
<?php
if($module->showtitle){
?>
<div class="modtitle">
<div class="fleche">
<span>
<?php
echo $module->title;
?>
</span>
</div>
</div>
<?php
}
?>
<div class="modcontent">
<?php echo $module->content; ?>
<div class="clear">
</div>
</div>
</div>
<?php
}
?>
make different functions names that sets different values if needed.
the function name will match the syle you set:
modChrome_includeposition($module, &$params, &$attribs)
because
style="includeposition"
inside of your jdoc.
I'm trying to figure out how to make a div invisible when someone goes to www.mysite.com/examplepage.php, but is visible when someone goes to www.mysite.com/example.php?added=1. Could someone be wonderful enough to explain this to me? The purpose of the div is give a message to users directed to the ?added=1 page - oddly enough something this useful is surprisingly hard to find instructions for. I'm a beginner, so if it's a simple thing to do I'd be really appreciative if someone gave me an example piece of code that would do this.
Thanks a lot
In your HTML/PHP template...
<?php if (isset($_GET['added']) AND $_GET['added'] == '1'): ?>
<div>
...
</div>
<?php endif; ?>
Though it would be better to process the flag in some controller code and then set a flag, so you don't have to use the isset() and the $_GET directly in your view.
<?php if (isset($_GET['added']) && $_GET['added'] == 1): ?>
<div>thediv!</div>
<?php endif ?>
Should get your started. The $_GET['added'] == 1 is optional in your case though.
<?php if (#$_GET['added'] == 1): ?>
<div>thediv!</div>
<?php endif ?>
Can also be used as a shorter version (although I would recommend just using only isset($_GET['added']) in your case, since I doubt you care about the =1 at the end).
The above answers are correct, but if you need to hide it but leave it in the source, something like this:
<div <?php if ($_GET['added']==1)echo "style='display:none'"; ?>>
hidden from the page, visible in view source.
</div>
there are several reasons one want to leave it in the source, such as showing the div when certain button clicked.