Using PHP as Template Engine and having a thin Template - php

I'm using PHP as a template engine per this suggestion: https://stackoverflow.com/a/17870094/2081511
I have:
$title = 'My Title';
ob_start();
include('page/to/template.php');
$page = ob_get_clean();
And on page/to/template.php I have:
<?php
echo <<<EOF
<!doctype html>
<html>
<title>{$title}</title>
...
EOF;
?>
I'm trying to remove some of the required syntax from the template pages to make it easier for others to develop their own templates. What I would like to do is retain the variable naming convention of {$variable} but remove these lines from the template file:
<?php
echo <<<EOF
EOF;
?>
I was thinking about putting them on either side of the include statement, but then it would just show me that statement as text instead of including it.

Well, if you want a VERY simple templating solution, this might help
<?php
$title = 'My Title';
// Instead of including, we fetch the contents of the template file.
$contents = file_get_contents('template.php');
// Clone it, as we'll work on it.
$compiled = $contents;
// We want to pluck out all the variable names and discard the braces
preg_match_all('/{\$(\w+)}/', $contents, $matches);
// Loop through all the matches and see if there is a variable set with that name. If so, simply replace the match with the variable value.
foreach ($matches[0] as $index => $tag) {
if (isset(${$matches[1][$index]})) {
$compiled = str_replace($tag, ${$matches[1][$index]}, $compiled);
}
}
echo $compiled;
Template file would look like this
<html> <body> {$title} </body> </html>

Related

How to change TITLE dynamically after the header is included [duplicate]

This question already has answers here:
How to dynamically change a web page's title?
(20 answers)
Closed 8 years ago.
I would like to change the title of the HTML page based on the content, but im including only the content below the header part, so i have to change the title from this included php. To explain:
<html>
<header><title>I would like to change</title></header>
<!--CONTENT-->
<?
include "pages/some_page.php";
?>
</html>
How could i do that? Anyone can help in this?
You cant do that without a nasty hack.
What you should do is perform all your logic BEFORE you output html. A simple example follows:
<?php
//index.php
//perform logic and set variables before any html
$page = isset($_GET['menu'])?$_GET['menu']:'home';
switch($page){
case 'home':
$title = ' welcome to myco.ltd';
$content = 'pages/home.php';
break;
case 'about':
$title = 'about us';
$content = 'pages/about.php';
break;
case 'contact':
$title = 'get in touch';
$content = 'pages/contact.php';
break;
}
//the following html could be in a separate file and included, eg layout.php
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<!--menu and other shared html here-->
<?php include $content;?>
<!-- shared footer stuff here-->
</body>
</html>
This is essentially a VERY barebones router script, an essential component of any framework. I would highly recommend you consider a lightweight framework rather than write everything from scratch. http://fatfreeframework.com/home would be a great start
The function below will let you change document title, meta keywords and meta description. You may use it anywhere in your application.
Just be sure to turn on output buffering using ob_start() before the function is called. I prefer including it at the top of application, just after all global settings are loaded.
function change_meta_tags($title, $keywords, $description){
$output = ob_get_contents();
if (ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/", "/<meta name=\"keywords\" content=\"(.*?)\" \/>/", "/<meta name=\"description\" content=\"(.*?)\" \/>/");
$replacements = array("<title>$title</title>", "<meta name=\"keywords\" content=\"$keywords\" />", "<meta name=\"description\" content=\"$description\" />");
$output = preg_replace($patterns, $replacements, $output);
echo $output;
}
Use javascript in some_page.php .
<?php echo "<script>document.title = '".$dynamicTitleVariable."';</script>"; ?>
Pending what you are trying to base the content off of, this could easily be done via an MVC-style setup. In your controller, you would generate the title based off of content that could be grabbed and pass this through to the view as a variable. Then, in your view have the title be dynamically set:
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
</html>
This should also work fine with SEO capability, as crawlers will be able to interpret this far better than they would JavaScript.

PHP create a nicer way to echo variables

I am looking for a way to replace <?php echo $something; ?> with another notation like {$something}. But: No smarty or sth similar is used!
More detailed:
At the moment, I got a .php file (with some variables inside), which includes the file "template.php". In this template file, I don't want having to use the (not very user-friendly) php notation, but replace certain strings inside this file like mentioned above. Is there any way to do so? It would be probably the best, if you could replace strings like <title></title> with <title><?php echo $title; ?></title>.
Maybe (my thoughts) I should just write the whole code into a php variable, then do some preg_replace and echo it? Or is there a more beautiful solution?
Did a similar thing several years ago wherein I had to replace several variables in an email template. What I ended up implementing was doing a str_replace on several tags. Like you, I don't want to have PHP notations or to escape characters in the template file as much as possible
Example:
template.php
<html>
<head>
<title>[EMAIL_TITLE]</title>
</head>
<body>
Hello [USER_NAME],
Login here [LOGIN_LINK].
</body>
</html>
processor.php
$body = file_get_contents( 'template.php' );
str_replace( '[EMAIL_TITLE]', $emailTitle, $body );
str_replace( '[USER_NAME]', $userName, $body );
str_replace( '[LOGIN_LINK]', $userName, $body );
I've sinced changed implementation though to make use of PHP short tags. Using the same previous example, you could try:
template.php
<html>
<head>
<title><?= $params['title']; ?></title>
</head>
<body>
Hello <?= $params['userName']; ?>!
</body>
</html>
processor.php
$params = array(
'title' => $siteTitle,
'userName' => $userName
);
ob_start();
require_once( 'template.php' );
$body = ob_end_clean();
There are a few notations you can try. One that I prefer for templates is simply:
<?php
echo <<<HTML
<html>
<head>
<title>$title</title>
</head>
<body>
$body
</body>
</html>
HTML;
?>
And then in your content file, you do something like:
<?php
$title = 'My Page!';
$body = '<p>My Content!</p>';
include './template.php';
?>
With this, you don't have to escape singe and double quotes, and it's easy to make changes later.
You can also read in the file to a string and use preg_replace like you said. The easiest way would be with an array to manually go through the file and pull out the place holders. But this is a slow solution if you have high traffic and a lot of variables.

Execute PHP code in a String without Eval

Currently developing a "simple" template class, the problem is how would I execute PHP code within a string without using eval?
A following example is how my template class works:
$user = 'Dave';
ob_start();
include 'index.tpl';
$content = ob_get_clean(); // String
$pattern = sprintf('/%s\s*(.+?)\s*%s/s', '{{', '}}'); // replace with php tags
$new_content = preg_replace($pattern, '<?php echo $1; ?>', $content);
echo $new_content;
index.tpl
<html>
<head></head>
<body>
Hello {{ $user }}!
</body>
</html>
I get the following result:
Hello !
I don't want to use eval because how slow and bad it is to use, is there any other way of doing this? laravel blade engine does not use eval so there must be.
Thanks,
Joel.
You don't need to execute PHP Code. You replace your {{ $user }} with PHP code, which doesn't get executed anymore. So your HTML will look like this after the replace:
<?php echo "Dave" ?>
Your Browser thinks <?...> is an HTML-tag and thus doesn't display the correct name.
Solution:
Just replace {{ $user }} with Dave, why do you want to add more PHP Code?
I suggest to you when you assign a value to a variable, you should put it as a global variable like this;
$GLOBALS['My_Vars']['VarName'] = $Value;
when you retrevie the name of the variable from your code which is in your example $user, you change {{ $user }} to the value within $GLOBALS['My_Vars']['user']
in this case you don't need to use evel

Add to page title tag based on variable from URL

I have seen the following thread but it's a bit beyond me...
How can I change the <title> tag dynamically in php based on the URL values
Basically, I have a page index.php (no php in it just named to future proof - maybe now!). It contains numerous lightbox style galleries which can be triggered from an external link by a variable in the URL - e.g. index.php?open=true2, index.php?open=true3, etc.
I would like the index.php title tag - to include existing static data + append additional words based on the URL variable - e.g. if URL open=true2 add "car gallery", if URL open=true3 add "cat gallery", if URL has no variable append nothing to title.
Can anyone assist? I have been searching but either missed the point of posts or it hasn't been covered (to my amateaur level).
Many thanks. Paul.
At the top of your php script put this:
<?php
# define your titles
$titles = array('true2' => 'Car Gallery', 'true3' => 'Cat Gallery');
# if the 'open' var is set then get the appropriate title from the $titles array
# otherwise set to empty string.
$title = (isset($_GET['open']) ? ' - '.$titles[$_GET['open']] : '');
?>
And then use this to include your custom title:
<title>Pauls Great Site<?php echo htmlentities($title); ?></title>
<title>Your Static Stuff <?php echo $your_dyamic_stuff;?></title>
<?php
if( array_key_exists('open', $_GET) ){
$title = $_GET['open'];
}else{
$title = '';
}
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
The content of the document......
</body>
</html>
http://www.w3schools.com/TAGS/tag_title.asp
http://php.net/manual/en/reserved.variables.get.php
PHP can fetch information from the URL querystring (www.yoursite.com?page=1&cat=dog etc). You need to fetch that information, make sure it's not malicious, and then you could insert it into the title. Here's a simple example - for your application, make sure you sanitise the data and check it isn't malicious:
<?php
$open = "";
// check querystring exists
if (isset($_GET['open'])) {
// if it does, assign it to variable
$open = $_GET['open'];
}
?>
<html><head><title>This is the title: <?php $open ?></title></head>
PHP has lots of functions for escaping data that might contain nasty stuff - if you look up htmlspecialchars and htmlentities you should find information that will help.
Some of the other answers are open to abuse try this instead:
<?php
if(array_key_exists('open', $_GET)){
$title = $_GET['open'];
} else {
$title = '';
}
$title = strip_tags($title);
?>
<html>
<head>
<title><?php echo htmlentities($title); ?></title>
</head>
<body>
<p>The content of the document......</p>
</body>
</html>
Otherwise as #Ben has mentioned. Define you titles in your PHP first to prevent people from being able to directly inject text into your HTML.

How to insert php include inside heredoc variable?

I need to have include page inside the php heredoc variable but it doesn't work please help me.
$content = <<<EOF
include 'links.php';
EOF;
You can do this way:
ob_start();
include 'links.php';
$include = ob_get_contents();
ob_end_clean();
$content = <<<EOF
{$include}
EOF;
Simple: you cannot do it. You can include the file before hand, store it in a variable, then insert it into the file. For example:
$links_contents = file_get_contents('links.php');
//$links_contents = eval($links_contents); // if you need to execute PHP inside of the file
$content = <<<EOF
{$links_contents}
EOF;
What do you mean by not working? As in contents of 'links.php' isn't in $content? If thats what you want try using output stream redirection (or just read the file).
<?php
ob_start();
include 'links.php';
$content = ob_get_contents();
ob_end_clean();
echo "contents=[$content]\n";
?>
Heredoc syntax is made to handle text only. You can't include a file or execute php methods in it.
Resources :
php.net - heredoc
Do not use heredoc at all.
if you need to output your contents - just output it as is, without storing it in the variable.
There can be very limited use of output buffering and I am sure here is not such case.
Just prepare your data and then output it using plain HTML and PHP.
make your pages like this (right from the other recent answer):
news.php:
<?
include "config.php"; //connect to database HERE.
$data = getdbdata("SELECT * FROM news where id = %d",$_GET['id']);
$page_title = $data['title'];
$body = nl2br($data['body']);
$tpl_file = "tpl.news.php";
include "template.php";
?>
template.php:
<html>
<head>
<title><?=$page_title?></title>
</head>
<body>
<? include $tpl_file?>
</body>
tpl.news.php
<h1><?=$page_title?></h1>
<?=$body?>
<? include "links.php" /*include your links anywhere you wish*/?>

Categories