Using PHP in HTML files - an uncommon way - php

I've seen several scripts during my time as a web programmer (I'm still new though) which had PHP included in an uncommon way.
The PHP was not added the usual way like <div><?php echo $foo; ?></div>, but this way: <div>{FOO}</div> or this <div>{$foo}</div>.
I am wondering how I could achieve such a thing? I really want to learn this thing.
Can someone direct me to the correct sources to learn this?
Thanks.

It has to be a template engine? You inject values to it from a PHP script. Smarty is a basic example.
For example, from your PHP page, you write :
include('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('foo', 'Bar Baz');
$smarty->display('index.tpl');
And, your template page would look like
<div>{foo}</div>
with .tpl extenstion.
When the program is run, the template variable {foo} will be replaced by its assigned value "Bar Baz"

The Developer must have been using a Template Engine Such as Smarty
You can even define arrays:
{assign var=foo value=[1,2,3]}
Objects
{$foo->bar}
The following would help you get started
http://www.9lessons.info/2011/09/smarty-template-engine-using-php.html
http://www.dreamincode.net/forums/topic/255552-an-introduction-to-smarty-php-template-engine/
http://www.moskalyuk.com/blog/smarty-faq
http://www.youtube.com/watch?v=5xLfvY8upsQ (Video)

Related

PHP short way to echo string?

In PHP we echo strings this way :
echo 'string';
But i saw PHP frameworks like Laravel and scripts echo strings using Curly Brackets :
{string}
How i can do that without using any PHP framework?
It's not necessary to use Curly Brackets if there is other way to short echo!
I prefer code examples.
PHP has a few methods to print strings, such as (but not limited to) print, and echo or just shorthand <?= "str" ?>.
The bracket print that you ask about from laravel is not per say in php.
That is from a template engine called Blade.
So the {} way of printing stuff is not possible in php.
You will have to stick to the standard ways or use a template engine!
You can short echo by
<?= $variable; ?> when you open a new php tag
or you use, as described in your question a framework such as laravel - that's pretty much it
What you can do, but I'm not really sure if it's a good idea - write a function like:
function x($string) {
echo $string;
}
x('Test'); // will output Test
The short answer is you can't do that with PHP. PHP provides language constructs to output to standard output, etc. PHP doesn't provide a pre-processor. Most template frameworks are a pre-processor meaning that they convert your {<STRING>} into an echo $x statement.
So either create your own template framework, or stick to PHP's API.
After researching i found a Template Engine called Smarty that allows me to echo using Curly Brackets
First i created 2 files index.php , template.html
Then i moved the folder /libs that i downloaded from the template page to my script directory
and in my index.php i required the Smarty.class file
require_once "libs/Smarty.class.php";
then i called the Smarty class :
$smarty = new Smarty;
after that i pushed the variable :
$smarty ->assign("name",'Amr');
and i displayed the template file index.html
$smarty ->display("template.html");
at the end i wrote in the index.html <p>{$name}</p> and it outputted : Amr

Separating php from html

I am building a website using php. I would want to separate the php from the html. Smarty engine, I guess does that, but right now its too complicated for me. Looking for a quick fix and easy to learn solution, one which is an accepted standard as well. Anyone helping please.
Consider frameworks or choose a template engine
Use a framework. Depending on your project, either a micro framework like Slim or something more complete like Laravel.
What I sometimes do when writing complex systems with quite much php code is separating it the following way (don't know your exact project, but it might work for you):
You create a php file with all the functions and variables you need. Then, you load every wepgage through the index.php file using .htaccess (so that a user actually always loads the index.php with a query string). Now, you can load the html page using file_get_contents (or similar) into a variable (I call this $body now); this variable can be modified using preg_replace.
An example: In the html file, you write {title} instead of <title>Sometext</title>
The replacement replaces {title} with the code you actually need:
$body = str_replace('{title}', $title, $body);
When all replacements are done, simply echo $body...
Just declare a lot of variables and use them in the template:
In your application:
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}
In user.tpl.php:
User name: <?=$username?><br>
Full name: <?=userFullName?><br>
Age: <?=$userAge?>
By putting it in a function, you can limit the scope of the variables, so you won't pollute your global scope and/or accidentally overwrite existing variables.
This way, you can just 'prepare' the information needed to display and in a separate php file, all you need to do is output those variables.
Of course, if you must, you can still add more complex PHP code to the template, but try to do it as little as possible.
In the future, you might move this 'render' function to a separate class. In a way, this class is a view (a User View, in this case), and it is one step in creating a MVC structure. (But don't worry about that for now.)
Looking for a quick fix and easy to learn solution
METHOD 1 (the laziest; yet you preserve highlighting on editors like notepad++)
<?php
// my php
echo "foo";
$a = 4;
// now close the php tag -temporary-
// to render some html in the laziest of ways
?>
<!-- my html -->
<div></div>
<?php
// continue my php code
METHOD 2 (more organized; use template files, after you passed some values on it)
<?php
// my php
$var1 = "foo";
$title = "bar";
$v = array("var1"=>"foo","title"=>"bar"); // preferrable
include("template.php");
?>
template.php
<?php
// $var1, $var2 are known, also the array.
?>
<div>
<span> <?php echo $v["title"]; ?> </span>
</div>
Personally, i prefer method 2 and im using it in my own CMS which uses lots and lots of templates and arrays of data.
Another solution is of course advanced template engines like Smarty, PHPTemplate and the likes. You need a lot of time to learn them though and personally i dont like their approach (new language style)
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}

PHP - phrases/word translations in a file, best way to do it.. array, variables?

I am developing a multi-langual website. Language variables (phrases/word translations) will be entered in a specific file (one different file for each language)
I wanted to know the best way to enter the phrases/word translations, should I use a normal array?
e.g
Filename = English.php
<?php
$translations = array();
$translations['phrase1'] = "this";
$translations['phrase2'] = "that";
..
?>
and in the template file
<?php
include("English.php");
echo $translations['phrase1'];
etc...
I am pretty new to PHP so I am just looking for the best way to do it.
Any suggestions?
Thank you for your help!
There are multiple of ways to do this, the two things that pop-off my head right now are:
1) Have a look at gettext & GNU gettext page. An example implementation of this to look at is Aur Website of ArchLinux. They their app support multiple languages & its all dynamic. user can can switch between languages easily. The source code is available here, study it & see how they did it.
2) Other option could be use a framework like cakephp, as most of these frameworks have translations support
Hope it somewhat helps

php,mysql , and smarty. Confused by a "{" in social-engine platform

hi I was looking at a php code from social engine and they have something like this:
header("Location:user_event.php?event_id={$event_id}&justadded=1")
why id it not
header("Location:user_event.php?event_id=$event_id&justadded=1")
or
header("Location:user_event.php?event_id=".$event_id."&justadded=1")
because the value of $event_id is correct but when the page redirects I go to:
user_event.php?event_id=&justadded=1
now I'm sure I did something to mess the value of {$event_id} but I don't even know what it means. does it have to do with smarty?
Using {$variable} inside of double quoted strings, is for two reasons:
a) to prevent mistakes like:
$variable = "prefix";
header("Location:somepage.php?value=$variable_name"); // PHP would actually look for a variable called $variable_name instead of the desired $variable
b) allowing to insert variables of arrays and objects into the string without interrupting it
header("Location:somepage.php?value=$myObject->someValue"); // this wouldn't work
header("Location:somepage.php?value={$myObject->someValue}"); // this works
But all of this shouldn't have any effect with Smarty, because Smarty only parses { } entities inside of the template files and header("Location: ...."); definitly doesn't belong there, unless you have a {php}header("Location:...");{/php}
If you have the later one, than you have to access the $event_id differently, because it's not accessible from inside the Smarty class, unless you assign it first with
$smarty->assign('event_id', $event_id);
than either
{php}
$event_id = $this->get_template_vars('event_id');
header("Location:user_event.php?event_id={$event_id}&justadded=1");
{/php}
or
{php}
global $event_id;
header("Location:user_event.php?event_id={$event_id}&justadded=1");
{/php}
But having this kind of code inside the template is quite wrong. Usually such stuff should be done in the actuall php file before the template is ever called.

Constructing arrays in Smarty PHP

Is it possible to construct an array in Smarty, for example I have tried
{def $totalitems[0]=3}
But that doesn't seem to work. Is it possible in Smarty?
Thanks.
I'm not sure why you would want to do this. The idea behind a template system is that you are separating the logic from the display. You need to build the array in PHP and then pass it into your smarty template using php like this:
$totalitems[0]=3;
$smarty->assign("totalitems",$totalitems);
Then you can access totalitems from within your template in the normal fashion.
In Smarty3 Beta you can do the following:
Examples:
{$foo['bar']=1}
{$foo['bar']['blar']=1}
Just look at the README: http://smarty-php.googlecode.com/svn/branches/Smarty3Dev/distribution/README
I am not sure if you can do it in Smarty2. I have tried a few things on my version of Smarty2, but it doesn't work. You might need to upgrade to Smarty3.
However, I would recommend against doing logic operations in the template, if it can be helped.

Categories