Search code examples
phptemplatesblogstemplate-engine

Making a php template for blog page


I'm quite new to the whole php scene but I have managed to make a php header and footer and include them on my pages so I dont have to edit the header and footer on each page now. My next challenge is making a whole template for something like a blog page where if I change the template then all the blog pages will change accordingly but the content will of course have to remain the same much like the php header and footers I have. I have read a bit about theme engines etc but they all seem to be quite confusing, and I don't wish to convert it to wordpress. So what are my options as to making a template? thank you in advance.


Solution

  • You can simply use smarty, powerfull template engine for PHP. First - create template with html base, header, footer. Save it to templates/_Frame.html

    <!DOCTYPE html>
    <html>
        <head>
            <title>{block name='Title'}{/block} - My website</title>
        </head>
        <body>
                        <div>Header and some other stuff</div>
            {block name='Content'}{/block}
                        <div>Footer and some other stuff</div>
        </body>
    
    </html>
    

    Then, crate a template file for each page. If its a blog with same look on each page and the only variable thing is the post content - you need only 1 template. Lets call it 'Post.html'

    {extends '_Frame.html'}
    {block name='Title'}{$Post.Title|escape}{/block}
    {block name='Content'}{$Post.Content}{/block}
    

    In php - do such thing:

    <?php
    
        //Lets say at this poin you've got $BlogPost = array('Title' => 'Blog post title', 'Content' => 'Body of blog post')
        $S = new Smarty();
        $S->assign('Post', $BlogPost); //This creates new variable $Post which is availible inside templates.
        $S->display('Post.html'); //this displays your template
    ?>
    
    
    |escape - escapes all html in variable < goes ^lt; etc.