How to separate HTML from PHP files?

Possible duplicate: (now deleted)
What is the best way to separate PHP code and HTML?

I am new to PHP, but I know that separating HTML and PHP code is a good solution. You can probably help me on this. For example, I have this code:

$username = "Welcome to my world"; (index.php) <div>{HOW TO DISPLAY HERE $username?}</div>(index.html) 

I know that I need to use a class and create some kind of template inside, but I don’t know how to do it

+4
source share
6 answers

MVC / Template System

As indicated in other answers, I would recommend using a template engine like smarty. I would also advise you to learn about the concept of the model, representation, control used in many modern PHP frameworks, such as CodeIgniter, Laravel or Zend.

Your own template system

You can also create your own little "template system". Here is a very simple example of how you can create templates.

index.php

 <?php $username = "Welcome to my world"; $html = file_get_contents("template.html"); // opens template.html $html = str_replace("{{username}}", $username, $html); // replaces placeholder with $username echo $html; ?> 

template.html

 <html> <body> <div>{{username}}</div> </body> </html> 
+11
source

You just need to put the variable between the <?php and ?> Tags. i.e:

 <div><?php echo $username; ?></div> 
+3
source

Use a template system like Smarty or Twig .

Edit: you can just echo the values:

 <?php echo $variable; ?> 

But then you need to work with the included ones, and this is not the best way. You might look at a structure like Symfony2 using Twig or Zend2 or something else.

+1
source

There are several ways to do this using placeholders, frameworks, or the like. However, the most important part will be saving the actual logic from the layout file. If you developed your code correctly, you just need to have a few echoes in the "html" file .:-)

+1
source

You can use smarty framework. Here is the link: www.smarty.net

0
source

What the OP seems to be looking for is one of many MVC infrastructures that separate the program logic from the display logic and make Smarty more understandable.

MVC stands for Model View Controller and is the so-called pseudo-design pattern. This is a way to clearly encode your application logic and have only minimal output code in the template files.

The model refers to the logic of the database (or some other data warehouse). Part of the controller is what is used to talk to the Model, and provide data for the View output. Smarty templates can be used as a View component quite well, and Smarty has its own syntax for use with PHP.

There are many MVC-like frameworks such as Zend , CakePHP, and Kohana . Also, check out the Smarty Template Engine or, alternatively, ExpressionEngine .

For more information on MVC, refer to Wikipedia - Model-view-controller .

0
source

All Articles