+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Simple template system

  1. #1
    Full Member dzone is on a distinguished road
    Join Date
    Dec 2003
    Posts
    75

    Lightbulb Simple template system

    Hello,

    Imagine you need to write a news script. You are not a sloppy coder so you have to separate the HTML from the PHP. There is a very easy way to write a simple template system.

    I assume you have something like this in your "template" folder:

    Code:
    news.tpl
    
    ..............
    <p>{NEWS_TEXT}<br>
    <i>{NEWS_DATE}</i>
    </p>
    <hr>
    ..............
    Then when you have got the text and date from, let's say mySQL you do the following:

    PHP Code:
    define("TEMPLATE_NEWS""template/news.tpl");

    //............

    // Get the template
    $tpl_news my_file_get_contents(TEMPLATE_NEWS);

    // Parse the template
    $tpl_news str_replace("{NEWS_TEXT}"$news_text$tpl_news);
    $tpl_news str_replace("{NEWS_DATE}"$news_date$tpl_news);

    echo 
    $tpl_news;

    // The implementation of the file_get_contents() available in PHP 4.3, but
    // the latest PHP is not installed everywhere, right?
    function my_file_get_contents($filename) {

        
    $fp fopen ($filename"rb");
        
    $contents fread ($fpfilesize ($filename));
        
    fclose ($fp);

        return 
    $contents;

    This can be optimize, e.g. you could write a function parse_template($tpl, $replace) where $replace is an associative array like:

    PHP Code:
    $replace = array(
      
    "{NEWS_TEXT}" => $news_text,
      
    "{NEWS_DATE}" => $news_date,
    ); 
    and then make a loop like

    PHP Code:
    foreach ($replace as $key => $value) {
      
    $tpl str_replace($key$value$tpl);

    But I've said simple, isn't it?

    Hope that helps,
    Z.
    ------------------------------------
    [URL=http://www.dedicatedzone.com]Managed Dedicated Servers[\URL]

  2. #2
    Full Member amish_geek is on a distinguished road
    Join Date
    Jan 2004
    Posts
    20
    Interesting... I havent come across how that is done yet in my 2 years of coding. Then again I never really looked for it. Hmm.. now I'm going to have to try that the next time I re-do a site entirely from scratch!
    Aaron Abramson
    Hosting Made Easy

  3. #3
    Full Member dzone is on a distinguished road
    Join Date
    Dec 2003
    Posts
    75
    Hello,

    Glad that helped somebody. But I would like to strees that this system is really handy for some small modules or scripts.

    I use that for news scripts, feedback forms etc., but if I need a templating system for the site I use Smarty. You should definitively have a look on its homepage: http://smarty.php.net/ . Deep down it uses the samw principles that my approach, but has a lot of cool extra features.
    ------------------------------------
    [URL=http://www.dedicatedzone.com]Managed Dedicated Servers[\URL]

  4. #4
    Newbie Dan is on a distinguished road
    Join Date
    Jan 2004
    Posts
    1
    Interesting, handy to use.. Smarty's okay, but really too bulky for small sites.

    I'm still partial for include();

  5. #5
    Full Member dzone is on a distinguished road
    Join Date
    Dec 2003
    Posts
    75
    Hi!

    Smarty's okay, but really too bulky for small sites.
    Yeah, right... That's why I normally use it on large sites

    I'm still partial for include();
    include() is good, but has many downsides. E.g. you will need to mix up HTML with PHP (instead of using wildcards like {YOUR_THING}), it's insecure and then, your PHP in templates will get corrupted if you'll try to write a simple CMS with WSYWIG editor like HTMLarea...
    ------------------------------------
    [URL=http://www.dedicatedzone.com]Managed Dedicated Servers[\URL]

  6. #6
    Moderator airnine is on a distinguished road
    Join Date
    Jan 2004
    Posts
    78
    well guys, I'm big on php and

    here is a nice little tip for you all hooked on include();

    include_once("somefile.php");

    good luck

    Airnine
    -------------------------------
    Airnine is a developer @
    www.promomedium.com
    -------------------------------

  7. #7
    Full Member Interactive is on a distinguished road
    Join Date
    Jan 2004
    Location
    Sierra Vista, AZ, USA
    Posts
    74
    Pretty simple, but I think that may get a little resource intensive after a while.

    I built a template system for several different sites for a client of mine, basically just a nice little class that would cache the templates. Works great and on a somewhat active site (35k page views a day) it had no problems.

  8. #8
    Full Member AdulteratedJedi is on a distinguished road
    Join Date
    Jan 2004
    Posts
    9
    Anyone ever stop to realise that PHP is a template engine. thats the way it was made

    AJ

  9. #9
    Full Member dzone is on a distinguished road
    Join Date
    Dec 2003
    Posts
    75
    basically just a nice little class that would cache the templates
    Well.. That's the next step done in Smarty If you want to share your code to give an idea to the beginners then you're welcome

    Anyone ever stop to realise that PHP is a template engine. ...
    "Anyone ever stop to realise that computer is a typewriter? thats the way it was made " That's equavalent to what you've just said...?

  10. #10
    Full Member Interactive is on a distinguished road
    Join Date
    Jan 2004
    Location
    Sierra Vista, AZ, USA
    Posts
    74
    Originally posted by AdulteratedJedi
    Anyone ever stop to realise that PHP is a template engine. thats the way it was made

    AJ
    That was what Rasmus designed it for. Then Zend took over and steered it in the direction we're heading today.

    I'll post my class when I get back, at class right now.
    -Robert Norton
    http://www.HostComb.com - Find The Hosting Provider That Meets Your Needs

  11. #11
    Full Member AdulteratedJedi is on a distinguished road
    Join Date
    Jan 2004
    Posts
    9
    "Anyone ever stop to realise that computer is a typewriter? Thatís the way it was made " That's equivalent to what you've just said...?
    Well no, not really. A computer can be defined as a device that computes, especially a programmable electronic machine that performs high-speed mathematical or logical operations or that assembles, stores, correlates, or otherwise processes information. A Calculator could be a computer... a typewriter could not.

    I spend a lot of time over at the Site Point Forums especially in the Advanced PHP forum, and have learnt a great deal. This lesson about template engines being one of them, I will quote some stuff that I have learnt.

    To me template engines like Smarty are a complete waste of time. If we had to pay they would be a complete waste of money as well, fortunately these packages are freely available (For the Most Part). These so-called ďtemplate enginesĒ do not add any special features to PHP that are not already there, and by using them, dynamic web sites become more complex, a lot slower, and harder to maintain.

    What does a template engine enable us to do? It allows us to separate content from business logic by supplying it with a template file. The template file is a normal HTML file, with special symbols (variables) in it instead of traditional content, and with special control structures (or: blocks) to influence the presentation logic.

    To use a template file with Smarty you would have to do:
    PHP Code:
    // Business code (index.php)
    require_once('Smarty.class.php');
    $smarty =& new Smarty();
    $smarty->assign('title''Smarty Test');
    $smarty->assign('name''AdulteratedJedi');
    $smarty->display('index.tpl');

    // Presentation (index.tpl)
    <html>
      <
    head>
        <
    title>{title}</title>
      </
    head>
      <
    body>
        <
    h1>{title}</h1>
        <
    p>Hello All Iím {name}</p>
      </
    body>
    </
    html
    The following code, is completely equivalent, runs much faster, is much clearer, and doesn't use a third-party template engine at all:

    PHP Code:
    // Business code (index.php)
    $title   = 'Template Engine Test');
    $name = 'AdulteratedJedi');
    include('index.tpl');

    // Presentation (index.tpl)
    <html>
      <head>
        <title><?= $title ?></title>
      </head>
      <body>
        <h1><?= $title ?></h1>
        <p>Hello All Iím <?= $name ?></p>
      </body>
    </html>
    A lot of you will probably say: "Yeah, right! This may work for simple examples as these, but for more complicated web sites, template engines are a real asset!" That is not true. The example I gave can easily be extended to larger, complex sites. Why is this possible? Because PHP already is a template engine. Examine all template engines you can think of, and compare their features with those of PHP. PHP has them all. And a lot more.

    So why do people think we need a template engine? The answer to that question is very simple: PHP has become too complex. Back in the old days, when PHP4 was just PHP/FI, the language was nothing more than a simple template engine. It had variables and blocks, and that was about it. Now, after a couple of years, PHP has been added to (but nothing was removed!) - it now has classes - and a large function library was written. And the latter is where the problem lies.

    Pick any book on PHP from a shelf in your local bookstore, and look how result rows from a MySQL database are printed. (MySQL is of course the DBMS used in those books, which should already give you a clue about how bad the book is.) The mysql_-functions are used all over the place in the presentation layer.

    Here, in these forums, we have tought people to not use those mysql_-functions directly, but use a database abstraction layer instead. This makes coding simpler (no need to know all those functions for the various DBMS's) and when they decide to use another DBMS instead of MySQL (and they undoubtedly will at some point), the conversion will be painless. What is the result of those lessons? People no longer use those functions directly, so that's good. On the other hand, they still place their business logic all over the presentation code. That's not so good. Most people don't know what to do about it, until they learn about those yucky template engines. No need to carry on here...

    At this point I also like to point out that saying "The layout must be strictly separated from the content" is a moot point. What is the layout? That's the colours, the fonts, the styles and so on. The plain HTML itself is the content. A couple of years ago cascading style sheets were introduced, and using these makes it possible to cleanly separate content from layout. I can change 99% of the layout of any of my sites by just changing the style sheet; there is no need to dive into the HTML. Only if the site needs a major overhaul the HTML must be changed. If your web designer tells you this isn't true, fire him.

    Another answer to the question "Why do people think we need a separate template engine?" is the following: the biggest part of the PHP community (and the ASP community, for that matter) knows nothing about software architecture. Most of the PHP programmers don't know what an O(n^2) algorithm is, or who Donald Knuth is, or why a sorting algorithm can never be faster than O(n log n), or how Dijkstra's shortest path algorithm works. If they don't know the answers to these basic questions, how can we expect them to know how the design a software program? I'm not saying the majority of the community consists of a bunch of idiots, because that certainly isn't true. There are lots of bright, intelligent people out there, but they just don't know how to write software, because that isn't in their field of expertise. And can we blame them? Of course not. People who use PHP aren't software developers to begin with.

    Here are some questions/remarks you may have had when reading this rant, and answers for them.

    Q: If you use variables like '$title', as in your example, all over your code, then the business logic becomes a mess, and there is a possibility of clashes between such variables.
    A: Then don't use these (global) variables. With little effort you can set up a simple class (or other structure) that store the values for the page you are creating, allowing you to nicely separate presentation code from the business code.

    Q: The 'better' template engines have a cache to make loading of pages much faster. Clean PHP doesn't do this, so the template engine is, in that case, faster!
    A: Incorrect. The cache in a template engine is needed to store the parsed template in some other format (Smarty uses PHP for that), which can then be instantly restored. With clean PHP the format is already correct, so there is no need to use a cache. Less and simpler lines code, faster execution.

    Q: Instead of using a template engine-specific language, our web designers - who know nothing about programming - are now required to have knowledge of PHP! We can't have that, now can we?
    A: Why not? The template engine-specific language is nothing more than a minimal programming language with an ugly syntax. It has variables, conditionals, loops, and maybe even functions. As PHP is a full programming language, it has all of these constructs, and more. But that doesn't mean you require your web designers to know all there is to know about PHP. The set of requirements doesn't change at all. Just the basics will be enough. The added benefit is that if they want to, your web designers can start experimenting with PHP (or other scripting languages) much faster.

    Q: You said maintaining a web site generated by some template engine is harder to maintain instead of easier. Why?
    A: One reason is that an additional software package is involved. At least one person must be able to work with it. More knowledge is required. Also, not only the web site and PHP must be kept up to date; the template engine itself must be maintained as well. This means more work. Another reason is that the best solution for any problem is always the simplest one. Using a large, complex template engine where PHP itself suffices is not a simple solution. In other words: more work yet again.

    A lot of what has been said here was by a very valuable person over at sitepoint (in my opinion) called voostind, and I agree with him 100% reading his posts has taught me a lot. He, like me, uses an Object Orientated approach to solve most programming problems. Without a doubt he is one of the smartest PHP programmers over there, heís just gotten his Masters Degree in Computer Science, and has been studying software architecture for years. So I think you can all agree he knows what he is talking about.

    AJ

  12. #12
    Full Member dzone is on a distinguished road
    Join Date
    Dec 2003
    Posts
    75
    AdulteratedJedi

    Although I don't agree with everything, my respect for your speech =)

    A computer can be defined as a device that computes
    OK, my fault. I should have said "a calulator". I meant that PHP is now much more powerful than just an advanced templating solution and sometimes it's suitable for other employment, e.g. I write some kind of "shell scripts for Windows" in PHP (working in the FAR console, similar to MC on Linux).

    And then, you haven't covered another important subject. I use my very simple templating class to make possible the use of WSYWIG editors like htmlarea. You see, if the company is big it can hire a designer/webmaster knowing PHP and stuff to handle everything to be done with the website. But if the company is small and you need to make a website so the secretary who doesn't even know the word "PHP" can modify contents and add news.... you need a CMS. Yes, not a monster like postnuke (a waste of time just like Smarty?), but a simple overlaying templating class, isn't it?

  13. #13
    Full Member AdulteratedJedi is on a distinguished road
    Join Date
    Jan 2004
    Posts
    9
    I meant that PHP is now much more powerful than just an advanced templating solution and sometimes it's suitable for other employment
    I agree Completely. Any programmer who uses PHP soley as a templating solution, in my opinion, is obviously not a very good one, and is certainly not doing the language justice.

    How simple of a class are we talking ?? fancy posting it I agree a simple templating class can do the job, i must admit i still have a semi-intermidiate (ie does morte than a simple class) in place on some sites. You may wish to have a look at This post for another solution

    I never said templates themselves are useless; I said third-party template engines are useless, which is something quite different. I don't see why people think its easier for a web designer to write '{title|function}' (Smarty) instead of '<?= function$title) ?>' (PHP). Tthe latter is supported better by applications used by web designers, as for example Dreamweaver supports PHP, but not Smarty. There's nothing wrong with templates. On the contrary, using them is probably a good idea. But as PHP is a template engine in itself, why would you need a third party one? I really don't see why it would be easier for someone to learn a specific template engine's language instead of a bit of plain, basic PHP. On a sidenote: I never use the <?= tag myself (most good PHP'ers dont either) it is possible to disable this tag, but find me one ISP running PHP that does that.

    At the end of the day it all comes down to personal preference, and what solution is best for you. My point, and many others too, is why should you force your designers to learn the smarty language, rather than learning PHP, even if they just learn the basics .. its still better than making them learn smarty, isnt it ?

    AJ

  14. #14
    Full Member jamesmarshal1 is on a distinguished road
    Join Date
    Feb 2011
    Posts
    5
    Include () is good, but has many downsides. Eg you will need to mix HTML with PHP (instead of using wildcards such as {YOUR_THING}), it is unsafe then, its like the PHP HTMLarea WSYWIG editor you try to write a simple CMS templates will be corrupted ...</span>

  15. #15
    Full Member BarbaraShorenw is on a distinguished road
    Join Date
    Apr 2011
    Posts
    5
    Here, in these forums, they have tought people to not use those mysql_-functions directly, but use a database abstraction layer in lieu. This makes coding simpler (no need to know all those functions for the various DBMS's) and when they choose to make use of another DBMS in lieu of MySQL (and they without a doubt will at some point), the conversion will be painless. What is the result of those lessons? People no longer use those functions directly, so that is nice. On the other hand, they still place their business logic all over the presentation code. That is not so nice. Most people don't know what to do about it, until they learn about those yucky template engines. No need to over on here...

+ Reply to Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts