Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I don't use a template engine with my PHP, what should my code look like?

Tags:

php

templates

I don't want to use an MVC framework. I don't want to use a template engine. I am a few man shop where the developers where all the hats, no graphic artists. We do it all (all layers). I do not want code mixed with presentation, like I have with Classic ASP.

But, I do not know what my code is suppose to look like between server side and the actual presentation.

If I'm not emitting HTML in my server side code, how does it get to the HTML page so I can do things like <span><?= $myvar ?></span>? and put loops in the html page?

Thank you for any advice.

like image 724
johnny Avatar asked Feb 23 '23 01:02

johnny


2 Answers

For using loops and all, I use the alternative syntax for the control structures.

An example:

<div id="messages"<?php if(!(isset($messages) && count($messages))): ?> class="hidden"<?php endif; ?>>
    <?php if(isset($messages)): ?>
    <?php foreach($messages as $message): ?>
    <div class="message"><?php echo $message; ?></div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

For more information, see this: http://php.net/manual/en/control-structures.alternative-syntax.php

Oh also, I use a semi-MVC structure, where I have a class that handles templates (views), basically it's just a class that I create an instance of, pass a set of variables, then render the template when the instance get destroyed. I have an array of variables in that class, and then use extract to pass all variables in the include, like so:

extract($this->variables, EXTR_SKIP);
include($this->file);

EDIT: Here is the same example in Smarty:

<div id="messages"{if isset($messages) && !count($messages)} class="hidden"{/if}>
    {if isset($messages)}
    {foreach from=$messages item=message}
    <div class="message">{$message}</div>
    {/foreach}
    {/if}
</div>
like image 91
jValdron Avatar answered Apr 28 '23 07:04

jValdron


Simple PHP projects usually generate the full HTML in-place instead of populating templates, so you'd just echo it out in your PHP code.

This gets messy, so you WILL end up coding some kind of templating system for any moderately complex website.

A possible alternative is to serve your page as completely static HTML/CSS and use AJAX to fetch the actual contents dynamically (JSON would be a good transport format, it's native to JS and can easily be generated from PHP). This gets you rid of all the HTML littered across your PHP code. Whether this is a viable alternative or not depends on the case.

like image 43
Alexander Gessler Avatar answered Apr 28 '23 06:04

Alexander Gessler