Dynamic Titles in my codeigniter header.php - php

I have a header.php I'm loading in my controllers for every page. However I want to have dynamic titles for each page. My idea was to pass a $title variable into the view as I'm loading it:
//Home Controller
function index()
{
$data['title'] = "Dynamic Title";
$this->load->view('header', $data);
$this->load->view('layouts/home');
$this->load->view('footer');
}
and then check for the $title variable in my header.php
<title>
<?php if ($title)
{
echo $title;
}
else
{
echo 'Default Title';
}
endif; ?>
</title>
However this doesn't work and I get a blank page. I think it is my syntax for the header.php but I can't figure out why.

Proper if Syntax
Your syntax on the if-statement is a bit off. You can use either:
if (condition) {
// do a
} else {
// do b
}
Or
if (condition) :
// do a
else :
// do b
endif;
You seem to have transposed the ending of the latter onto the former.
Using the Ternary Operator in Title
Once you've made that change, your title can be printed as easily as:
<title><?php echo isset($title) ? $title : 'Default Title' ; ?></title>
Alternative View Loading
Another method of loading views is to work with a single template file:
$data['title'] = 'Foo Bar';
$data['content'] = 'indexPage';
$this->load->view('template', $data);
This loads the template.php file as your view. Within this file you load your subsequent parts:
<?php $this->load->view("_header"); ?>
<?php $this->load->view($content); ?>
<?php $this->load->view("_footer"); ?>
By no means is this necessary, but it may help you maintain brevity in your controller.

Well I would try doing a var dump of $title in the view, just to see if it's getting passed at all.
Also, you don't need "endif;" since you're ending the if statement with the last curly brace.

Related

echo variable before call function

First of all I should say this code is a sample and i remake for you to show what i want my original code too huge and can't post here, but the logic and functions similar to this example.
I made a dynamic title in a function called getTitle() and it show on #side-bar now i want to use this title in h1 tag too, but as you see h1 tag rendered before this function, and i'm not able to move h1 tag after #side-bar. Now i want to know how can i echo a variable that generated from a function, before call this function.
PHP:
<?php
function getTitle(){
global $title;
// some code to generate dynamic title
$title = "example title";
echo $sample = "123";
return $title;
// other code
}
?>
HTML:
echo <h1><?=$title;?></h1>;
<div id="side-bar"><?php getTitle(); ?></div> <!-- call -->
I know if i move $title after calling the function getTitle(); it works fine but i need to echo $title before calling this function. Is it possible? or any idea, or logic to do this?
Also i know i can clone the title from side-bar to h1 with javascript or etc.. but this is a h1 tag and can't fill it after page load in client side.
PHP:
<?php
function getTitle(){
// some code to generate dynamic title
return ['title' => 'Example title', 'sample' => '123'];
}
?>
HTML:
$response=getTitle();
echo <h1><?=$response["sample"];?></h1>;
<div id="side-bar"><?php $response["title"]; ?></div> <!-- call -->
Your approach is wrong. Instructions are not executed after return statement.
PHP function
<?php
function getTitle(){
$title = /*generate dynamic title*/;
return $title;
}
?>
HTML
<?php $generatedTitle = getTitle(); ?>
<h1><?php echo $generatedTitle; ?></h1>
<div id="side-bar"><?php echo $generatedTitle; ?></div>

PHP Vars From Included Bootstrap Not Showing Up in View

I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....
if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....
Somethings I noticed from similar questions:
- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)
Any ideas are greatly appreciated, I am pulling my hair out over here lol...
Source Code
https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa
If you just want to display your site name, I think you can use a constant like that :
define('SITE_NAME', "Jeff's Site");
And then display it in your index.tpl :
<?php echo SITE_NAME; ?>
Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :
class JLR_Core_Views
{
private $data;
public function loadView($templatePath, $data = array())
{
$this->data = $data;
$templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
if(file_exists($templatePath)) {
// Yes, I know about the vuln here, this is just an example;
ob_start();
include_once $templatePath;
return ob_get_clean();
}
}
function __get($name)
{
return (isset($this->data[$name]))
? $this->data[$name]
: null;
}
}
Then, you can call your template like that :
$view = new JLR_Core_Views();
$view->loadView("index", array("sitename" => "Jeff's Site"));
And here is your index.tpl :
<?php echo $this->siteName; ?>
Below is another example of what you can do.
First, you create this class in order to store all the variables you want :
<?php
class JLR_Repository {
private static $data = array();
public function set($name, $value) {
self::$data[$name] = $value;
}
public function get($name) {
return (isset(self::$data[$name]))
? self::$data[$name]
: null;
}
}
?>
Then, when you want to store something in it :
JLR_Repository::set("sitename", "Jeff's Site");
And in your index.tpl :
<?php echo JLR_Repository::get("sitename"); ?>
try using the 'global' keyword - http://php.net/manual/en/language.variables.scope.php

Displaying a drupal page without the template around it in Drupal 7

I'd like to render the contents of a "basic page" in drupal. Something like this question: displaying a Drupal view without a page template around it but for Drupal 7.
My attempt almost works:
function mytheme_preprocess_page(&$variables, $hook) {
if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
$variables['theme_hook_suggestions'][] = 'page__ajax';
}
}
And have a file named page--ajax.tpl.php in the same directory where template.php lives:
<?php print $page['content']; ?>
The problem is that it still renders the menu and my two custom blocks from the sidebar. I only want the page content. What should I change?
You are almost there. The only thing you need is to add a custom HTML wrapper template.
Add a function to template.php:
function THEMENAME_preprocess_html(&$variables, $hook) {
if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
$variables['theme_hook_suggestions'][] = 'html__ajax';
}
}
Create a file named html--ajax.tpl.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">`
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php print $styles; ?>
<?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>">
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $page_bottom; ?>
</body>
</html>
Flush all caches. That's all.
Based on the answer of Ufonion Labs I was able to completely remove
all the HTML output around the page content in Drupal 7 by
implementing both hook_preprocess_page and hook_preprocess_html in
my themes template.php, like this:
function MY_THEME_preprocess_page(&$variables) {
if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {
$variables['theme_hook_suggestions'][] = 'page__embed';
}
}
function MY_THEME_preprocess_html(&$variables) {
if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {
$variables['theme_hook_suggestions'][] = 'html__embed';
}
}
Then I added two templates to my theme: html--embed.tpl.php:
<?php print $page; ?>
and page--embed.tpl.php:
<?php print render($page['content']); ?>
Now when I open a node page, such as http://example.com/node/3, I see
the complete page as usual, but when I add the response_type
parameter, such as http://example.com/node/3?response_type=embed, I
only get the <div> with the page contents so it can be embedded in another page.
Shamelessly taken form here :
displaying a Drupal view without a page template around it (second best answer for drupal 7).
Alexei solution still use the page template wich is in charge of displaying blocks

Zend Framework, passing variables to view

I have a problem with displaying a view. When I pass var to view, view doesn't render.
Controller:
public function indexAction()
{
$branchModel = new Application_Model_Branches();
$branches = $branchModel->getAllBranches();
$this->view->menu = $branches;
}
View (index.phtml):
<h2>Menu</h2>
<?php
$this->htmlList($this->menu);
?>
When I try debug $branches without assign it to view, all seems to be ok, but when I try push it to view,index.phtml don't appear.
Regards
You're just missing an echo in your code, the htmlList view helper returns a value - it doesn't echo it. Some examples of the various form view helpers can be seen here
<h2>Menu</h2>
<?php
echo $this->htmlList($this->menu);
?>
controller
$this->view->variableName = "Hello World!";//assign here
$this->view->assign('variableName1', "Hello new World!");//assign here
view
echo $this->variableName;//echo here
echo $this->variableName1;//echo here

What is the best way to include a php file as a template?

I have simple template that's html mostly and then pulls some stuff out of SQL via PHP and I want to include this template in three different spots of another php file. What is the best way to do this? Can I include it and then print the contents?
Example of template:
Price: <?php echo $price ?>
and, for example, I have another php file that will show the template file only if the date is more than two days after a date in SQL.
The best way is to pass everything in an associative array.
class Template {
public function render($_page, $_data) {
extract($_data);
include($_page);
}
}
To build the template:
$data = array('title' => 'My Page', 'text' => 'My Paragraph');
$Template = new Template();
$Template->render('/path/to/file.php', $data);
Your template page could be something like this:
<h1><?php echo $title; ?></h1>
<p><?php echo $text; ?></p>
Extract is a really nifty function that can unpack an associative array into the local namespace so that you can just do stuff like echo $title;.
Edit: Added underscores to prevent name conflicts just in case you extract something containing a variable '$page' or '$data'.
Put your data in an array/object and pass it to the following function as a second argument:
function template_contents($file, $model) {
if (!is_file($file)) {
throw new Exception("Template not found");
}
ob_start();
include $file;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
Then:
Price: <?php echo template_contents("/path/to/file.php", $model); ?>

Categories