I'm working on codeigniter and I wonder whats the best way to change title dynamically. Eg. title will change depending if you are on home page, single post page, category pages, etc.
The only solution i can think of is to make separate function and compare current URL ( from address bar ) with structure of the single post page, category page, home page
Something like this:
public function current_title() {
if($this->uri->segment(2) == 'post') {
// will return post title
}
if($this->uri->segment(2) == 'category') {
// will return archive title
}
if(current_url() == base_url()) {
// this is home page
}
If anyone worked with this before, any advice highly appreciated
I would not use the uri for this, but instead the controller and action name and the language class :
public function current_title()
{
$this->lang->load('titles.php', 'en');
return $this->lang->line(
$this->router->fetch_class().'.'.$this->router->fetch_method()
);
}
You will have a key like MyClass.myMethod for your translation. Just add your titles in your titles.php file :
$lang['MyClass.myMethod'] = "The title";
$lang['MyOtherClass.myOtherMethod'] = "The other title";
Read more about translation :
http://ellislab.com/codeigniter/user-guide/libraries/language.html
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html
//in the controller you should do like this:
class Home extends your_Controller {
public function __construct() {
parent:: __construct();
}
function index()
{
$this->data['pageTitle'] = 'Your page title';
$data['main_content'] = 'home';
$this->load->view('includefolder/viewname', $data);
}
}
This is how I do it:
$PHPFile = basename($_SERVER['PHP_SELF'],'.php');
switch ($PHPFile) {
case 'index': $PageTitle = 'Home'; break;
case 'products': $PageTitle = 'Products'; break;
case 'services': $PageTitle = 'Services'; break;
}
You can use string searches or whatever is needed. I use this method since I have the header of the page as a function in library.
As we have a controller function for each view so you can easily get function name from url
$this -> router -> fetch_module();
so you can work with it.
Related
In cakePHP 4
I have a controller and view.php connected with it.
I can use a route like this: sitename.com/projects/45, where 45 - is sample project ID.
Using this url I can reach a page with the content of particular project. But If I want to construct something like a page of settings of this project, how I have to do it?
For example via url sitename.com/projects/45/settings
Help please
It's simple:
// sitename.com/projects/45
// public function view($id) { ... }
// sitename.com/projects/45/settings
public function view($id, $passed = null) {
if($passed == 'settings') {
// do ...
}
}
or
public function view($id) {
$passed = $this->getRequest()->getParam('pass');
if (in_array('settings', $passed)) {
// do ...
}
}
i am stuck in segments in codeigniter because it is new to me,
the problem with my login form.
i gave the url in action like action="blog/login/getLog" and
my login form shows in the url like blog/login
i know that in controller class i just create a function like with the name login but i created my controller file like this:
class Blog extends CI_Controller{
function __construct(){
parent::__construct();
}
// Now See
function _remap( $method ){
$this->load->view('header');
switch( $method ){
case 'about':
$this->load->view('about');
break;
case 'login':
$this->load->view('login');
break;
case 'services':
$this->load->view('service');
break;
}
$this->load->view('footer');
}
}//Close Class
but now don't know how to handle both segment like login and login/getLog .
EDIT: What happen exactly, when i click on the login button then i just see the login form according to _remap() and the url like blog/login and when i submitted the form and the url looking like blog/login/getLog, the login form still looking but i want to redirect it on success.. or want to detect the segment getLog if possible in the case 'login': if possible.
Thanks in advanced.
If you are sending through the URL, just use uri class:
$var = $this->uri->segment(3);
If you are sending in a form, send the variable through the form. Perhaps a hidden field?
$var = $this->input->post('var_name');
Edit: I'm not quite sure why you are using _remap for this w/o routing to another function (you are only trying to call a view file instead)
This is how I would expect to see the login form:
<?php echo form_open('blog/login');?>
<input type="hidden" name="getLog" value"true" />
<input type="submit" value="Login" />
</form>
Then in your Blog class i would rather put a function
public function login() {
if($this->input->post('getLog') === "true") {
//the form was submitted, let's check the login?
}
else {
//probably don't need an else, but form isn't submitted
}
}
Edit 2:
In case there are confusions and you actually want to use remap. You can do it like this to get the variables also.
function _remap( $method ) {
if ($method == ‘something’) {
$this->something();
}
else {
$this->somethingelse();
}
}
function something() {
$var1 = $this->uri->segment(3);
$var2 = $this->input->post('some_variable_name');
}
class Blog extends CI_Controller{
function __construct(){
parent::__construct();
}
// Now See
function _remap( $method ){
switch( $method ){
case 'about':
$this->about(); <---------- here method (Add header, content, footer inside respective functions)
break;
case 'login':
$this->login(); <------- here too
break;
case 'services':
$this->service(); <----- here too
break;
}
}
}//Close Class
what you have done here is, you overrided the default behavior of URI by _remap function.
The overridden function call (typically the second segment of the URI)
will be passed as a parameter to the _remap() function:
Simply, in most cases, the 2nd segment will become $method in the _remap function.
so your form action will become.
action = "<?php echo base_url('blog/login');?>"
add index.php if you haven't removed index.php from your url by htaccess.
EDIT:
As per your question,
but now don't know how to handle both segment like login and login/getLog .
this is how you deal.
Any extra segments after the method name are passed into _remap() as an optional second parameter.
public function _remap($method, $params = array())
{
// all other segments will be in $paramas array
}
What is a simple way in CodeIgniter that I can return a specific content type for request URL extension? For example I want to return json if the url is http://example.com/phone/digits/1.json, html if the URL ends in /1 or /1.html, and XML if the URL ends in /1.xml. This will load a view in the format specified. So in the above example (phone/digits/1.json) would return the json version of the digits method. Here is what I've got so far that is NOT correctly working but gives an idea of what I'm going for. It's currently generating a 404 if no arguments are passed (/phone/digits.json)... Any suggestions would be appreciated.
class Phone extends CI_Controller {
public $layout = FALSE;
public function __construct()
{
if (preg_match('/\.(html|json)$/', $ci->uri->uri_string(), $matches))
{
$this->format = ('html' == $matches[1] || !isset($matches[1])) ? '' : '.json.php';
}
}
public function digits()
{
$this->load->view('phone/digits' . $this->format);
}
Updated for clarity,
I didint understand your question well, asuming you want to simplify your url
its solution for this url : http://domain.com/phone/digits.json (xml or html also)
But with few modification , it can be useful also with http://domain.com/phone/digits/n.json (n - id number)
in config/routes.php
$route['phone/digits.(json|html|xml|php)'] = 'Phone/digits/$1';
$route['phone/digits'] = 'Phone/digits';
Controller
class Phone extends CI_Controller {
public $layout = FALSE;
public function __construct()
{
//hmm
}
public function digits($format = '')
{
if($format == '') {
//default view or something else
}
else {
$this->load->view('phone/digits' . $format);
}
}
Parse the url
grab the extension
use a switch condtional and set relevant output
-
switch( $extension ){
case 'json':
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
break;
case 'xml':
$this->output
->set_content_type('application/xml')
->set_output(file_get_contents(some_xml_file.xml));
break;
// etc etc
}
I have a controller called user which just loads the user profile page for now
class user extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function index($username = null){
//load index page
$this->load->view('profile/index');
}
}
i have also routed it so i can load it from user/$username in routes
//user profiles pretty url
$route['user/(:any)'] = "user/index/$1";
the thing is i would like to change it and allow directly the users to go to their profiles without typing user/$username and instead $usernamd like mysite.com/$username...
I tried it but it messes up everything.how can i achieve this?
Thanks.
I guess the only way to achieve something like this is to add all other controllers to your routes file.
You could try something like this
$route['controller'] = "controller";
$route['controller/(:any)'] = "controller/$1";
$route['(:any)'] = "user/$1";
Combined with the _remap function as stated here. In your users controller.
Have you heard of the _remap function?
If you replace the index() function with this:
public function _remap($username = null) {
$this->load->view('profile/index');
}
It will probably work. You don't have to use the routes.php.
I used something like this for my users ; this "p" function in my users controller, mysite.com/users/p/$user_id , routes are good but I solved it like this, you could also do it do index function if you don't want something like "p"
function p()
{
$total_slashes = count ( $this->uri->segment_array () );
$last = end ( $this->uri->segments );
if ($total_slashes == 3) {
$data ['userdetails'] = $this->users_model->userDetails ( $last );
// $last is our user_id
$this->load->view('profile/index');
}
}
I am using Kohana 3.2 and I am having problems calling the ouput of a controller in another controller.
What I want...
In some pages I have got a menu, and in others I don't. I want to use make use of the flexability of the HMVC request system. In the controller of a page I want to call another controller which is responsible for the creation of the menu.
What I have a the moment:
file menu.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Menu extends Controller
{
private $_model = null;
public function __construct(Request $request, Response $response)
{
parent::__construct($request, $response);
$this->_model = Model::factory('menu');
}
public function action_getMenu()
{
$content = array();
$content['menuItems'] = $this->_model->getMenuItems();
// Render and output.
$this->request->response = View::factory('blocks/menu', $content);
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
}
}
somepage.php
public function action_index()
{
$this->template->title = 'someTitle';;
$contentData['pageTitle'] = 'someTitle';
$contentData['contentData'] = 'someData';
#include the menu
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
$this->template->content = View::factory('pages/somePage', $contentData);
$view = $this->response->body($this->template);
$this->response->body($view);
}
If I uncomment the following line in menu.php, I see the menu rendered:
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
So I guess that part is alright. The problem is in the following line in somepage.php:
$menuBlock = Request::factory('menu/getMenu')->execute();
This gives me back a response object. Whatever I do, I do not get the output in $this->template->menu.
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
What must I do to have $this->template->menu contain the view, so I can use it correctly?
I hope this all makes sense. This is the way I would like to do it, but maybe I am completely on the wrong track.
I would do it this way:
class Controller_Menu extends Controller
{
public function action_build()
{
// Load the menu view.
$view = View::factory('navigation/menu');
// Return view as response-
$this->response->body($view->render());
}
}
In your controller get the menu as follows:
// Make request and get response body.
$menu = Request::factory('menu/build')->execute()->body();
// e.g. assign menu to template sidebar.
$this->template->sidebar = Request:.factory('menu/build')->execute()->body();
I would not use the __construct method in your controllers. Use before() instead, this is sufficient for most of the problems (for example auth):
public function before()
{
// Call aprent before, must be done here.
parent::before();
// e.g. heck whether user is logged in.
if ( !Auth::instance()->logged_in() )
{
//Redirect if not logged in or something like this.
}
}
I found the answer to my problem in less than an hour after asking.
I just forgot to put it here.
In somePage.php change :
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
To:
$this->template->menu = Request::factory('menu/getMenuBlock')->execute()->body();
And in menu.php change:
$this->request->response = View::factory('blocks/menu', $content);
To:
$request = View::factory('blocks/menu', $content);
$this->response->body($request);
I hope this will help someone else.