How to correctly use PHP templating - php

I am new to PHP and I'm currently working through 'PHP for absolute beginners' book. In the book it is currently teaching about templating and using the StdClass() Object to avoid naming conflicts.
I have a file for templating called page.php and a file for my homepage called index.php.
My page.php code
<?php
return "<!DOCTYPE html>
<html>
<head>
<title>$pageData->title</title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>
</head>
<body>
$pageData->$content
</body>
</html>";
My index.php
<?php
//this correctly outputs any errors
error_reporting( E_ALL );
ini_set("display_errors", 1);
$pageData = new stdClass();
$pageData->title = "Test title";
$pageData->content = "<h1>Hello World</h1>";
$page = include_once "templates/page.php";
echo $page;
The errors i am receiving are
Warning: Undefined variable $title in C:\xampp\htdocs\ch2\templates\page.php on line 5
Warning: Undefined variable $content in C:\xampp\htdocs\ch2\templates\page.php on line 9
I don't understand this as it is exactly what the book is teaching any help would be appreciated and please if there are any better ways to use templating please remember I am a beginner so keep it simple!

Your page.php looks a little odd. return is not something I would use in context of printing html. Also, you are using php and html within the php tag which can't work. Try this:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageData->title; ?></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>
</head>
<body>
<?php echo $pageData->content; ?>
</body>
</html>
You don't need echo $page in your index.php, let the page.php do that.
/Edit: There is also a typo in line 9: $pageData->$content; I corrected that.

Related

Include 'count.html.php'

This book 'php and mysql novice to ninja' said that to include the files count.html and count.php, I must type the following into the bottom of the count.php file:
include 'count.html.php';
However, this does not seem to work unless it is just count.html without the .php.
Is this book accurate or not? I cannot find anything online about this way of including.
I've seen two separate lines of including tags such as:
include 'a.html';
include 'b.php';
Sorry for the shit formatting. I've never posted to this site before.
count.php:
<?php
$output = '';
for ($count = 1; $count <= 10; $count++) {
$output .= $count . ' ';
}
include 'count.html.php';
?>
count.html:
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title>counting to ten</title>
</head>
<body>
<p>
<?php echo $output; ?>
</p>
</body>
</html>
include looks for a file name exactly matching what you put in the quotes, it will not include two different files at once as you are describing.
Your count.html file contains PHP code in it, so it shouldn't have the .html extension, it would most commonly use .php or since it looks mostly like an html template file, you could use .phtml. The extensions .php and .phtml do the exact same thing, but generally by convention if you have a file exclusively with php code, you would name it .php, and it it has a lot of html, you might want to name it .phtml. Either is fine, but not the plain .html.
Assuming you decided to name it count.phtml, then your two files would then look like:
count.php
<?php
$output = '';
for ($count = 1; $count <= 10; $count++) {
$output .= $count . ' ';
}
include 'count.phtml';
?>
count.phtml
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title>counting to ten</title>
</head>
<body>
<p>
<?php echo $output; ?>
</p>
</body>
</html>
The author was showing his personnel method, which is confusing. Basically using the .php at the end of .html.php as a reminder to himself that it was related to the .php document. It made the html code appear as php, and the author was not the clearest.

Querying database without using echo, producing results for design

there's something that's giving me a bit of a headache at the moment. I am querying a database retrieving some data after clicking a link from a previous page.
Easy enough I get to play about with some code in the 'echo'. Problem is in the ‘echo’ as I need to put in php includes and general html/design code for design purposes. Is there a way or a method where I can write the code but then call variables again later and have the ability to place other php code such as includes? Basically something which is going to let me have to have the code but then allow me to concentrate on the design aspect of my page.
Any help much appreciated.
<?php
if(!empty($_GET['book_url']))
{
$sql = "
SELECT articles.id, articles.order_ref, articles.art_title, articles.art_book, articles.art_url, book.id AS bookid, book.book_name AS book_name, book.book_url AS book_url
FROM articles
LEFT JOIN book ON articles.art_book = book.id
WHERE book_name = \"" .$_GET['book_url'] . "\"
ORDER BY id ASC
";
// then do the query, etc....
}
$results = $db->query($sql);
if($results->num_rows) {
While($row = $results->fetch_object()) {
echo "
////////Show Stuff
";
?>
You can separate the code and the HTML by putting the code in <?php ?>. Then, in your HTML you can have short code snippets that print the work you did in the code sections. Like this (there might be a syntax error or two, I don't have Apache to test):
<?php
$name = $_GET['name'];
function stuff() {
// this would normally be long and complicated
return "stuff";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>title</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<!-- try to keep these short so you can focus on design-->
<h1>The name is: <?php echo $name; ?></h1>
<h1>The stuff is: <?php echo stuff(); ?></h1>
</body>
</html>
Alternatively, you can use a framework like Laravel which will provide a templating system.

View PHP file with includes included

Is there a tool that will show me what my .php file looks like AFTER the "preprocessor" goes through it and includes all the "include" and "require" files? In other words, if I have a file called "index.php":
<?php
#My root index page
include 'vars.php';
include 'header.php';
include 'body.php';
?>
If the files are:
vars.php:
<?php
SITENAME = "MySite";
$where = "here";
include 'ThatOne.php';
?>
header.php:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>My page</title>
</head>
body.php:
<?php
print "<body>\n";
print "<H1>Hello World</H1>\n";
print "</body>\n";
?>
ThatOne.php
<?php
$ThatOne = "This One";
?>
I would like to be able to see that this page results in a working page that looks like:
<?php
#My root index page
SITENAME = "MySite";
$where = "here";
$ThatOne = "This One";
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>My page</title>
</head>
<?php
print "<body>\n";
print "<H1>Hello World</H1>\n";
print "</body>\n";
?>
This is obviously a contrived example, but I am working with a site with includes that are nested about 4 deep, and I would like to make sure that what PHP is working with is really what I want it to be working with.
I am fairly new to PHP, but I asked this question of a colleague who is also working with PHP and his reaction was "That would be really usedful, but I have never seen anything that will show that."
If you wish, you may create your own tool. Just use get_included_files and file_get_contents, as follows:
<?php
#My root index page
include 'vars.php';
include 'header.php';
include 'body.php';
$included_files = get_included_files();
foreach ($included_files as $filename) {
echo file_get_contents( $filename );
}
?>
According to the manual, get_included_files() will get any required or required_once files, too (see here). The only limitation is that you'll only be able to see text or HTML output, so vars.php wouldn't have visible content. If you change a pure php file by giving it an extension of .phps, then you can see the PHP source code which can appear highlighted.

Weird HEREDOC output order

I am using (or at least tying to) PHP HEREDOC function as a templating engine. I have implemented external caller string that can directly process external functions in HEREDOC, and that works successfully.
The problem I am facing now is that the order of certain functions appear to take precedence and execute first, regardless of other functions and/or code inside the specific HEREDOC.
How to fix that?
(Please note I am a PHP beginner. I have done my homework, but couldn't find a solution. Thanks.)
FUNCTION PROCESOR:
function heredoc($input)
{
return $input;
}
$heredoc = "heredoc";
HEREDOC TEMPLATE:
function splicemaster_return_full_page()
{
global $heredoc;
$title ="This is document title";
echo <<<HEREDOC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{$heredoc(splice_html_title($title))}
</head>
<body>
{$heredoc(splicemaster_return_message())}
{$heredoc(splice_quick_add_article_form())}
{$heredoc(display_all_articles_in_a_html_table())}
</body>
</html>
HEREDOC;
}
The issue at hand is with "{$heredoc(display_all_articles_in_a_html_table())}" call, which outputs before everything else, resulting in a broken HTML.
Any help appreciated, I am banging my head with this for quite a while now.
UPDATE:
using stuff posted in comments i tried to do something else, but this is ugly as hell, and I would have issues editing this at later date.
function testout()
{
$title = "This is document title";
echo "<!DOCTYPE html>";
echo '<html lang="en">';
echo "<head>";
echo '<meta charset="utf-8">';
echo "<title>". $title . "</title>";
echo "</head>";
echo "<body>";
echo splicemaster_return_message();
echo splice_quick_add_article_form();
echo display_all_articles_in_a_html_table();
echo "</body>";
echo "</html>";
}
(How it looks like is not important - I have a HTML processor function.)
UPDATE 2
OK, so I found "dirty" fix, tho that doesn't explain why the engine works as it does. (I also tested on another machine, with diff. php):
function splicemaster_return_full_page()
{
global $heredoc;
$title ="This is document title";
echo <<<HEREDOC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{$heredoc(splice_html_title($title))}
</head>
<body>
{$heredoc(splicemaster_return_message())}
{$heredoc(splice_quick_add_article_form())}
HEREDOC;
echo <<<HEREDOC
{$heredoc(display_all_articles_in_a_html_table())}
</body>
</html>
HEREDOC;
}
You shouldn't be using heredoc here. Or really be trying to render an entire html document within a function. This is how html should be rendered with php.
Note: I'm also pretty sure you can't call functions in a heredoc statement.
<?php $title = "This is document title"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo splice_html_title($title); ?>
</head>
<body>
<?php
echo splicemaster_return_message()
. splice_quick_add_article_form()
. display_all_articles_in_a_html_table();
?>
</body>
</html>
You can see how much cleaner this is, which makes it much easier to edit, when needed. You just put this in a file 'page.php' for example.
include_once('page.php');
And include it where ever you would call that function splicemaster_return_full_page.
I asked this (similar) question on other site while seeking why this happens, and found the culprit.
The problem was in called functions that echo (or print) output, instead returning it. When I switched to return, the code outputs appropriately.

How can I access a variable in one block of PHP code in another block of PHP code in the same file?

I have something like this:
PHP code at the start:
<?php
$variable="example";
?>
Then HTML code:
<html>
<head>
<title>Title</title>
</head>
<body>
Then again PHP:
<?php
// code comes here, and I want to access variable $variable here.
?>
And then HTML code ends:
</body>
</html>
Is it possible to do this somehow? I don't want to create another file; I need to do this in this file.
Not Required unless if you are accessing it under functions ( as it will lose their scope)
test1.php
<?php
$var = 1;
//.. your code...
?>
<html>.....
<?php
echo $var; // prints 1
whereas the below code won't work...
<?php
$var = 1;
function displayVar()
{
echo $var; // You will get a notice .. !
}
Just do what you stated above and it will work.
<?php
$variable = 'Hello';
?>
<html>
<head>
</head>
<body>
<?php echo $variable; ?>
</body>
</html>
The above example will display a simple webpage with 'Hello' as the content. This is one of best strength of PHP actually.
try this
echo ($variable);
or
print($variable);
If it is the same file, yes it is possible, unless the variable is in a function. But this is a very simple question, that you could have tested yourself.

Categories