Two dynamic parts (template) - php

I don't know, how to descripe my problem, but I going to try.
I have build my own Template and with one part it is working, but I want to have two parts that are changing, if I click a link.
It is working on my index.php and if I click on the other links, but if I click on news to go back to news(it is my home (index.php)) I will get to a directory explorer.
a example:
my folder structure:
my htaccess:
RewriteEngine On
RewriteBase /inexorablez/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?site=$1 [L,QSA]
my navigation file:
<nav>
<ul>
<li>News</li>
<li>Teams</li>
<li>Downloads</li>
<li>Partner</li>
</ul>
</nav>
my index.php:
if( isset( $_GET['site'] ) ) {
$site = $_GET['site'];
} else {
$site = 'News';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>inexoarablez</title>
<link rel="stylesheet" href="unslider/dist/css/unslider.css">
<link rel="stylesheet" href="unslider/dist/css/unslider-dots.css">
<link rel="stylesheet" href="font-awesome-4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<!-- wrapper start -->
<div id="wrapper">
<div id="header">
<div id="col-left">
<!-- logo section start -->
<div id="logo-section">
<div id="logo"></div>
<h1>inexorablez</h1>
</div>
<!-- logo section end -->
</div>
<div id="col-right">
<!-- navigation start -->
<?php require( "includes/navigation.inc.php" ); ?>
<!-- navigation end -->
<!-- news start -->
<div id="news">
<?php
// Navigation
switch ( $site ) {
case 'News':
include( 'news/news.news.php' );
break;
case 'Teams':
include( 'news/teams.news.php' );
break;
case 'Downloads':
include( 'news/downloads.news.php' );
break;
case 'Partner':
include( 'news/partner.news.php' );
break;
default:
include( 'news/news.news.php' );
break;
}
?>
</div>
<!-- news end -->
</div>
</div>
<div id="main">
<div id="content">
<?php
// Navigation
switch ( $site ) {
case 'News':
include( 'sites/news.php' );
break;
case 'Teams':
include( 'sites/teams.php' );
break;
case 'Downloads':
include( 'sites/downloads.php' );
break;
case 'Partner':
include( 'sites/partner.php' );
break;
default:
include( 'sites/news.php' );
break;
}
?>
</div>
</div>
<!-- footer start -->
<footer>
fsdgdsfgfdsg
</footer>
<!-- footer end -->
</div>
<!-- wrapper end -->
<!-- scripts -->
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="unslider/src/js/unslider.js"></script> <!-- but with the right path! -->
<script>
jQuery(document).ready(function($) {
$('.my-slider').unslider({
autoplay: true
});
});
</script>
here a jsfiddle:
jsfiddle
Sorry for my english, I guess something is wrong, but I don't know really what...
If I go back to new, I will get this:
It is working on my index.php and all other links, but not on the "News" link, if I hit the "News" link I will get the folder structure.

If you want to disable directory listings, add this line to your .htaccess file(s)
Options -Indexes
You can have an .htaccess file in each directory
inexorablez/unslider/.htaccess
indexorablez/News/.htaccess
and/or at the root
indexorablez/.htaccess

Related

Quitting Smarty to do it manually

I am facing the problem that I'm not really sure how to develop without a framework or a template engine. I started coding that way and now I want to go to basics.
I used to work with this MVC schema, using Codeigniter and Smarty as a template engine. What I want to do now is to use raw php without both tools mentioned.
I don't know how to "copy" the concept of Smarty's "block" and "extends".
I used to define a base.tpl file which had html head, only the body tag, and the base css and js files (the ones that are always used in every page of the site), like this: (snippet)
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>Dashboard</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- ================== BEGIN BASE CSS STYLE ================== -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link href="{site_url()}assets/css/animate.min.css" rel="stylesheet" />
<!-- ================== END BASE CSS STYLE ================== -->
<!-- ================== BEGIN PAGE LEVEL CSS STYLE ================== -->
{block name='custom_css'}{/block}
<!-- ================== END PAGE LEVEL CSS STYLE ================== -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="{site_url()}assets/plugins/pace/pace.min.js"></script>
<!-- ================== END BASE JS ================== -->
</head>
<body>
<div id="page-container" class="fade page-sidebar-fixed page-header-fixed">
<div id="header" class="header navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
{include file='base/header.tpl'}
</div>
</div>
<!-- BEGIN PAGE -->
<div class="page-content">
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<!-- BEGIN PAGE TITLE & BREADCRUMB-->
{include file='admin/base/breadcrumb.tpl'}
<!-- END PAGE TITLE & BREADCRUMB-->
</div>
</div>
<!-- END PAGE HEADER-->
{block name='content'}{/block}
</div>
<!-- END PAGE CONTAINER-->
</div>
<!-- END PAGE -->
and then when I need to call this base.tpl I did this:
{extends file='base/base.tpl'}
{block name='custom_css}
<link href="{site_url()}assets/css/pages/blog.css" rel="stylesheet" type="text/css"/>
{/block}
{block name='content'}
<div class="row">
<div class="col-md-3 col-sm-6">
<div class="widget widget-stats bg-green">
<div class="stats-icon stats-icon-lg"><i class="fa fa-globe fa-fw"></i></div>
<div class="stats-title">TODAY'S VISITS</div>
<div class="stats-number">7,842,900</div>
<div class="stats-progress progress">
<div class="progress-bar" style="width: 70.1%;"></div>
</div>
<div class="stats-desc">Better than last week (70.1%)</div>
</div>
</div>
I have been searching but I am affraid I'm missing the right words to search because I am not finding answers.
I would like to be guided please!
Another way could be to do something like this. I feel like this is probably closer to what a template engine ends up with, but with using the {block} syntax instead.
index.php
<?php
$blocks = array();
function add_block($name, $callback){
global $blocks;
ob_start();
$callback();
$output = ob_get_flush();
$blocks[$name] = $output;
}
function get_block($name){
global $blocks;
if(!empty($blocks[$name])){
return $blocks[$name];
}
return '';
}
//stop any errors from being output.
ob_start();
//include the page code
include 'page.php';
$cleanup = ob_end_clean();
//now output the template
include 'template.php';
page.php
<?php
add_block('head', function(){
?><script type="text/javascript">/* Some JS */</script><?php
});
add_block('body', function(){
?><p>Some body text goes here</p><?php
});
template.php
<html>
<head>
<title>Site Title</title>
<?php echo get_block('head'); ?>
</head>
<body>
<?php echo get_block('body'); ?>
</body>
<?php echo get_block('after_body'); ?>
</html>
I'm not sure how smarty does it and have actually never used a templating engine myself. But maybe this could be how it's done.
Say we have:
index.php
page.php
template.php
When we go to index.php it could start and output buffer and include page.php. After the include catch the output buffer and use some regular expressions to match and blocks found within it and put them into variables.
Now do the same for the template.php and find all the blocks in there too and replace the blocks with the blocks found in page.php.
I don't actually think that's how templating engines do it. But that's one possible way.
A very tiny self made, templating engine
based on regex replace using an array hook
to "manually" parse templates
(but i grant you, smarty is more functional)
To any question, feel free to answer me here
The regex match whole file's term like {term-_},
and replace it by a php condition who will be executed on at rendering time.
if a mark" doesn't found in $vars, it will simply replaced by an empty string
Engine
function parse($vars, $tpl)
{
return preg_replace
(
'#\{([a-z0-9\-_]*?)\}#Ssie',
'( ( isset($vars[\'\1\']) )
? $vars[\'\1\']
: \'\'
);',
file_get_contents(TEMPLATE_DIR.$tpl)
);
}
part of index
<html>
<head>...</head>
{body}
</html>
part of body
<body>
<div class='ui'>{username}</div>
</body>
Usage
<?php
// include engine function
define("TEMPLATE_DIR", __DIR__."templates/");
require_once("library/parse.php");
// just init $vars on top of index
$vars = [];
// and access and fill it anywhere
$vars = ["username" => $_SESSION["user"]];
// prepare the body including previous $vars declarations
$vars["body"] = parse($vars, 'body');
echo parse($vars, 'index');
Output
<html>
<head>...</head>
<body>
<div class='ui'>Stack Overflow :)</div>
</body>
</html>
You can improve it by using constant and prevent double wrap marker {{}} or more, or placing debug trace...
Add this to start of engine to prevent templates containing object bracket can be bad interpreted as a templates marker :
$out = file_get_contents(TEMPLATE_DIR.$tpl);
$out = str_replace("{{}}", "{}", $out);
To use constant, you can use perform as like :
$empty = (DEBUG) ? "_EMPTY_" : "";
return preg_replace
(
'#\{([a-z0-9\-_]*?)\}#Ssie',
'( ( isset($vars[\'\1\']) )
? $vars[\'\1\']
: ( defined(\'_\'.strtoupper(\'\1\').\'_\')
? constant(\'_\'.strtoupper(\'\1\').\'_\')
: $empty
)
);',
$out
);
Note:
__DIR__
used in my code is valid for PHP >= 5.3.0 try
but you can use
dirname(__FILE__)
For PHP < 5.3.0 try

navigation include loop(php switch)

I am somewhere in a loop! My browser is including over and over again my navigation until the page crashes. I dont know why. I do the switch normally in the index.php, but I want to have an intro page and therfore I want to do it in the home.php.
Here is a pic of my folder structur:
Thats my index.php:
<body onload="main()">
<!-- Main content -->
<div id="main">
<!-- Logo -->
<div id="logo">
</div><!-- End Logo -->
<!-- h2 Webdesign & Development -->
<h1 id="text"></h1>
<!-- End h2 Webdesign & Development -->
<!-- Enter link -->
<div id="enter">
ENTER
</div><!-- End enter link -->
</div><!-- End main content -->
There is a "ENTER" Link to the real website(home.php)
Here is my navi.inc.php file:
<nav>
<ul>
<li><img data-other-src="../pics/home_button_hover.svg" src="../pics/home_button.svg" id="home" alt="Home Button"></li>
<li>Info</li>
<li>Projects</li>
<li>Contact</li>
</ul>
and finally my home.php:
<?php
require_once '../include/config.inc.php';
if( isset( $_GET['site'] ) ){
$site = $_GET['site'];
}else{
$site = 'Home';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Home | <?=$seiten_name?></title>
<link rel="stylesheet" type="text/css" href="../style/main.css">
<link href='http://fonts.googleapis.com/css?family=Iceland' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../js/image_switch.js"></script>
</head>
<body>
<div id="main">
<?php
// Navigation
switch ( $site ) {
case 'Home':
include('home.php');
break;
case 'Projects':
include('projects.php');
break;
case 'Contact':
include('contact.php');
break;
default:
include('home.php');
break;
}
?>
<div id="preloader">
<img src="../pics/ajax-loader.gif" alt="Preloader">
</div>
</div>
<?php
require('../include/navi.inc.php');
?>
</body>
</html>
Sorry for my poor english, but i hope you will understand my problem!! I want the home.php as my index :P
In your home.php file you have the following code:
switch ( $site ) {
case 'Home':
include('home.php');
break;
(Same goes for your default: block)
Which basically means that there's a situation where the home.php file will include itself, which will cause an infinity loop.

htaccess (not the index.php)

i am struggling with the .htaccess file. I have got an intro page as the index.php and there is a link. If you click the link, i want that you will get to the home.php. The home.php should be my real(pseudo) main index.php
Here is a pic of my folder structur:
On that picture you can see my .htaccess file and the folder structur. I am not sure, if the rules are correct.
Thats my index.php:
<body onload="main()">
<!-- Main content -->
<div id="main">
<!-- Logo -->
<div id="logo">
</div><!-- End Logo -->
<!-- h2 Webdesign & Development -->
<h1 id="text"></h1>
<!-- End h2 Webdesign & Development -->
<!-- Enter link -->
<div id="enter">
ENTER
</div><!-- End enter link -->
</div><!-- End main content -->
There is a "ENTER" Link to the real website(home.php)
Here is my navi.inc.php file:
<nav>
<ul>
<li><img data-other-src="../pics/home_button_hover.svg" src="../pics/home_button.svg" id="home" alt="Home Button"></li>
<li>Info</li>
<li>Projects</li>
<li>Contact</li>
</ul>
and finally my home.php:
<?php
require_once '../include/config.inc.php';
if( isset( $_GET['site'] ) ){
$site = $_GET['site'];
}else{
$site = 'Home';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Home | <?=$seiten_name?></title>
<link rel="stylesheet" type="text/css" href="../style/main.css">
<link href='http://fonts.googleapis.com/css?family=Iceland' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../js/image_switch.js"></script>
</head>
<body>
<div id="main">
<?php
// Navigation
switch ( $site ) {
case 'Home':
include('home.php');
break;
case 'Projects':
include('projects.php');
break;
case 'Contact':
include('contact.php');
break;
default:
include('home.php');
break;
}
?>
<div id="preloader">
<img src="../pics/ajax-loader.gif" alt="Preloader">
</div>
</div>
<?php
require('../include/navi.inc.php');
?>
</body>
</html>
Sorry for my poor english, but i hope you will understand my problem!! I want the home.php as my index :P
Please try below rule in your htaccess
DirectoryIndex home.php
This is working:
RewriteEngine On
RewriteBase /website/sites/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ home.php?site=$1 [L,QSA]

How to use different stylesheet for differenct divs on the same page and at the same time?

i am trying to use different style-sheet files in different divs at the same time. I have tried by using switch cases, but nothing helps, Please one thing to be notable that i have to show both of the divs at the same time
here is my code which i have tried so far:
<?php
switch ($type_show1):
case 'welcome1':
//default:
?>
<link href="css/main.css" rel="stylesheet" type="text/css" /> // css to include
<div class="page-header">
<div class="page-title">
<h5>Booking Management</h5>
<span>Good morning, Admin!</span>
</div>
</div>
<!-- /page header -->
<?php
break;
endswitch;
?>
<?php
switch ($type_show2):
case 'welcome2':
//default:
?>
<link href="css/main2.css" rel="stylesheet" type="text/css" /> // Other css to include
<div class="page-header">
<div class="page-title">
<h5>Booking Management</h5>
<span>Good morning, Admin!</span>
</div>
</div>
<?php
break;
endswitch;
?>
What's the difference in those stylesheets?
Guess you want something like this?
This way the divs are always shown and the stylesheets are only imported on your switch.
<?php
switch ($type_show1):
case 'welcome1':
//default:
?>
<link href="css/main.css" rel="stylesheet" type="text/css" /> // css to include
<?php
break;
endswitch;
?>
<?php
switch ($type_show2):
case 'welcome2':
//default:
?>
<link href="css/main2.css" rel="stylesheet" type="text/css" /> // Other css to include
<?php
break;
endswitch;
?>
<div class="page-header">
<div class="page-title">
<h5>Booking Management</h5>
<span>Good morning, Admin!</span>
</div>
</div>
<!-- /page header -->
<div class="page-header">
<div class="page-title">
<h5>Booking Management</h5>
<span>Good morning, Admin!</span>
</div>
</div>
Why aren't you declaring your 2 stylesheets on the head of your html, and giving two different IDs to your divs ?

How could I improve this template system?

At the moment, I have a base HTML template file. When ever I want to make a new page, I copy the template and place some require_once statements in between specific tags. I was wondering if there's a better way that would make it unnecessary to copy the template each time. Here's a typical example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title>Order a Ticket for the ball</title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text">introduction</div>
<div id="header_cell2">the process</div>
<div id="header_cell3">start</div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($config["directories"]["views"]."/index.form.view.php"));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($config["directories"]["views"]."/index.data.view.php"));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($config["directories"]["views"]."/index.side.view.php"));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
EDIT: I have taken note of your suggestions to use GET. The new idea is to have each request url formed as index.php?page=page_name. This request would then be dealt with by a main controller which then sets the variables of the template based on the value of $_GET['page']. For this, the template will now be:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title><?php h($title) ?></title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text"><?php h($header_1) ?></div>
<div id="header_cell2"><?php h($header_2) ?></div>
<div id="header_cell3"><?php h($header_3) ?></div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($view_1));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($view_2));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($view_3));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
Note: h() is a function that first of all removes all undesired entity tags before echoing a string.
On a related note, at the top of each page I have some controller files which are included with require_once. I was wondering if it would be possible to implement a function that simply includes files based on a specific input string (name of the functionality/page) i.e "index" in this way:
function include_controller($page){
switch($page){
case "index":
require_once(realpath($config["directories"]["controllers"]."/index_.php"));
break;
case "checkout":
require_once(realpath($config["directories"]["controllers"]."/checkout_.php"));
break;
default:
break;
}
}
Instead of hard coding the includes into each file, you could have a controller file in which you pass the page to be displayed through a $_GET variable. The controller then handles the logic and includes the appropriate page or pages. This is the way a lot of MVC frameworks do it.
Edit: To answer your second question, instead of using a switch, you could just check to make sure the file exists. If it does, include that file, otherwise output an error ("Page doesn't exists" or something similar).
function include_controller($page){
if (file_exists($config["directories"]["controllers"]."/$page_.php")) {
// page exists, include it
require_once($config["directories"]["controllers"]."/$page_.php"));
} else {
// page not found
}
}
Obviously you should probably make the function a little more robust and probably limit the files that will be included to a certain directory or something. Also make sure you properly filter the $page variable so users aren't able to access any file.
Keep this one file as your template file. Then for all the functionality in your site always hit this file. Lets sat this file is index.php. So all functionality requests go to index.php. But with different parameters so for functionality A.
index.php?function=a
For functionality b
index.php?function=b
you can add more parameters also.
Now on the basis of a,b and the set of parameters see what files you want to include as require once.
Like the others already said, it would be better to use some kind of MVC framework. Or at least use a template engine (e.g. Smarty). Your example is ok though, for the 90ies :)
You can get by with one template if you choose a different way of specifying what page is being requested, such as using a GET variable. You can load the pages in a database and specify each of the included pieces, then have one php 'template engine' that loads the requested page from the database and outputs the template with the right includes.
If your server supports it, you can references to things you want to include on all pages in .htaccess:
php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"
(Found this on codingforums.com)

Categories