I'm repeatedly having to include one variable when I display my views:
$this->load->view('login', array('logged_in' => $this->auth->is_logged_in()));
$this->load->view('somepage', array('logged_in' => $this->auth->is_logged_in()));
$this->load->view('anotherpage', array('logged_in' => $this->auth->is_logged_in()));
How can I include this one variable across all of my view outputs? Is there a simpler method than extending the templating class?
One simpler way would be to make the array into a variable, so you dont have to type it out all the time, e.g.
$params = array('logged_in' => $this->auth->is_logged_in());
$this->load->view('login', $params);
$this->load->view('somepage', $params);
$this->load->view('anotherpage', $params);
An alternative would be to create a Helper that returns whether a user is logged in. Helpers are globally available in your controllers and views. See http://codeigniter.com/user_guide/general/helpers.html and also
CodeIgniter: Create new helper?
how about using sessions?
$this->session->userdata($var);
or cookies
$this->input->cookie($var, TRUE);
thanks.
Great solution, Gordon! But, depending on the case, it's also possible to use the Most Simple Template Library.
Regards!
You can also access the class directly from within your view:
<?php if( $this->auth->is_logged_in() ): ?>
Hello!
<?php endif; ?>
It's not the greatest solution but I find it works well with user conditionals.
Related
Is there any way to set variables for the partial in the controller level?
Because everytime I need variables inside a partial I always have to pass them:
<?php
echo $this->partial('travels/_steps.phtml',
array('searchHotel' => $this->searchHotel,
'actionName' => $this->actionName))
?>
I would really just like actionName to be available on all partials - for instance.
You could extend the Zend_View_Helper_Partial class to a class that keeps that variable in scope. You would need to override the cloneView() function:
public function cloneView()
{
$view = parent::cloneView();
$view->actionName = $this->view->actionName
return $view;
}
You could use $this->render() instead. With it, you wouldn't need to pass the view variables every time.
Hope that helps,
You could also just sent the current view as a parameter to the partial:
<?php
echo $this->partial('travels/_steps.phtml', array('parentView' => $this));
Then, in the partial:
<?php
$view = $this->parentView;
echo $view->searchHotel, $view->actionName;
In my humble opinion, you're doing exactly what you're supposed to do - passing just those variables you'll need in the partial.
If this causes you pain, perhaps you might consider that you're using partials unnecessarily.
Or, put another way, if you want to have some variable available in all partials then perhaps the partial is not where you should be using those variables.
Maybe have a look at Placeholders and rethink how you go about rendering your views.
In most web applications we need global var base_url. In cakephp to get base_url currently i put the following code on beforeRender method in app_controller.php
function beforeRender(){
$this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));
}
Is there any alternative? Means is there any global variable available to get the base url rather than this?
Yes, there is. In your view, you may access:
<?php echo $this->webroot; ?>
Also, your host information is stored in the $_SERVER['HTTP_HOST'] variable in case you want that.
In your controller, if you want full URLs, use this:
Router::url('/', true);
Use anyone option below
<?php echo $this->Html->url('/');?>
<?php Router::url('/', true); ?>
<?php echo $this->base;?>
<?php echo $this->webroot; ?>
Define constant in Config/core.php as define("BASE_URL", "www.yoursite.com/"); and use BASE_URL anywhere in your project
and create a common helper with following functions
<?php
class CommonHelper extends AppHelper {
function get_url($url){
return BASE_URL.$url;
}
function get_src($url){
echo BASE_URL.$url;
}
}
?>
and use anywhere in project
$this->redirect($this->Common->get_url("login");
login
Don't forgot to include Common helper in controller
I recommend method 2 and 5 because they give complete url.
You may use
<?php echo Router::fullbaseUrl();?>
as well.
Refer http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html for more details.
Use Router::url('/', true) anywhere in your app.
Specifically in the View, you can use $this->Html->url('/', true) (or any other Helper in fact, the Helper::url method is inherited by all Helpers), which is just a wrapper for the above Router method.
In either case, the second true parameter causes it to return the full URL.
You can use
Router::fullBaseUrl()
If you have for example example.com/test and you want to ignore /test, you can use 'full' => false.
Also if you want to force ssl you can add '_ssl' => true.
i.e.
Router::fullBaseUrl(null, [ '_ssl' => true, 'full' => false]
Make sure you pass null as the first parameter as this is the base url in case you want to pass it.
note:
you need to import Router so you can use above function:
use Cake\Routing\Router
For most purposes I'd suggest using the CakePHP HtmlHelper to generate URLs, that way you won't need to worry about the base URL. The most user friendly way of getting the base URL in your view, however, would be <?php echo $html->webroot; ?>.
You can use FULL_BASE_URL constant.
Kohana (and probably other frameworks) allow you get a route and echo its URL, creating routes that are easy to maintain.
Contact
Is this OK to have in the view, or should I assign it to a variable, and then pass the view the variable?
Thanks
You aren't performing logic here. This is perfectly acceptable.
Of course your view code would be a bit cleaner if you created a variable in your controller, but this really is fine IMHO.
I find such a concatenation unnecessary. It seems url::base() going to be used in every link on the site. Why not to have a method to add it automatically? Something like Route::url("contact")
And usage of such a construct in the template is OK.
You can create a function or static method for generating urls:
public static function url($routename, array $params = NULL)
{
return url::base().Route::get($routename)->uri($params);
}
Pretty often I need to access $config variables in views.
I know I can pass them from controller to load->view().
But it seems excessive to do it explicitly.
Is there some way or trick to access $config variable from CI views without
disturbing controllers with spare code?
$this->config->item() works fine.
For example, if the config file contains $config['foo'] = 'bar'; then $this->config->item('foo') == 'bar'
Also, the Common function config_item() works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.
You can do something like that:
$ci = get_instance(); // CI_Loader instance
$ci->load->config('email');
echo $ci->config->item('name');
$this->config->item('config_var') did not work for my case.
I could only use the config_item('config_var'); to echo variables in the view
Your controller should collect all the information from databases, configs, etc. There are many good reasons to stick to this. One good reason is that this will allow you to change the source of that information quite easily and not have to make any changes to your views.
This is how I did it. In config.php
$config['HTML_TITLE'] = "SO TITLE test";
In applications/view/header.php (assuming html code)
<title><?=$this->config->item("HTML_TITLE");?> </title>
Whenever I need to access config variables I tend to use: $this->config->config['variable_name'];
echo $this->config->config['ur config file']
If your config file also come to picture you have to access like this for example I include an app.php in config folder I have a variable
$config['50001'] = "your message"
Now I want access in my controller or model .
Try following two cases one should work
case1:
$msg = $this->config->item('ur config file');
echo $msg['50001']; //out put: "your message";
case2:
$msg = $this->config->item('50001');
echo $msg; //out put: "your message"
$config['cricket'] = 'bat'; in config.php file
$this->config->item('cricket') use this in view
If you are trying to accessing config variable into controller than use
$this->config->item('{variable name which you define into config}');
If you are trying to accessing the config variable into outside the controller(helper/hooks) then use
$mms = get_instance();
$mms->config->item('{variable which you define into config}');
Example, if you have:
$config['base_url'] = 'www.example.com'
set in your config.php then
echo base_url();
This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).
I have a CakePHP application that in some moment will show a view with product media (pictures or videos) I want to know if, there is someway to include another view that threats the video or threats the pictures, depending on a flag. I want to use those "small views" to several other purposes, so It should be "like" a cake component, for reutilization.
What you guys suggest to use to be in Cake conventions (and not using a raw include('') command)
In the interest of having the information here in case someone stumbles upon this, it is important to note that the solution varies depending on the CakePHP version.
For CakePHP 1.1
$this->renderElement('display', array('flag' => 'value'));
in your view, and then in /app/views/elements/ you can make a file called display.thtml, where $flag will have the value of whatever you pass to it.
For CakePHP 1.2
$this->element('display', array('flag' => 'value'));
in your view, and then in /app/views/elements/ you can make a file called display.ctp, where $flag will have the value of whatever you pass to it.
In both versions the element will have access to all the data the view has access to + any values you pass to it. Furthermore, as someone pointed out, requestAction() is also an option, but it can take a heavy toll in performance if done without using cache, since it has to go through all the steps a normal action would.
In your controller (in this example the posts controller).
function something() {
return $this->Post->find('all');
}
In your elements directory (app/views/element) create a file called posts.ctp.
In posts.ctp:
$posts = $this->requestAction('posts/something');
foreach($posts as $post):
echo $post['Post']['title'];
endforeach;
Then in your view:
<?php echo $this->element('posts'); ?>
This is mostly taken from the CakePHP book here:
Creating Reusable Elements with requestAction
I do believe that using requestAction is quite expensive, so you will want to look into caching.
Simply use:
<?php include('/<other_view>.ctp'); ?>
in the .ctp your action ends up in.
For example, build an archived function
function archived() {
// do some stuff
// you can even hook the index() function
$myscope = array("archived = 1");
$this->index($myscope);
// coming back, so the archived view will be launched
$this->set("is_archived", true); // e.g. use this in your index.ctp for customization
}
Possibly adjust your index action:
function index($scope = array()) {
// ...
$this->set(items, $this->paginate($scope));
}
Your archive.ctp will be:
<?php include('/index.ctp'); ?>
Ideal reuse of code of controller actions and views.
For CakePHP 2.x
New for Cake 2.x is the abilty to extend a given view. So while elements are great for having little bits of reusable code, extending a view allows you to reuse whole views.
See the manual for more/better information
http://book.cakephp.org/2.0/en/views.html#extending-views
Elements work if you want them to have access to the same data that the calling view has access to.
If you want your embedded view to have access to its own set of data, you might want to use something like requestAction(). This allows you to embed a full-fledged view that would otherwise be stand-alone.
I want to use those "small views" to
several other purposes, so It should
be "like" a cake component, for
reutilization.
This is done with "Helpers", as described here. But I'm not sure that's really what you want. The "Elements" suggestion seems correct too. It heavily depends of what you're trying to accomplish. My two cents...
In CakePHP 3.x you can simple use:
$this->render('view')
This will render the view from the same directory as parent view.