Jump to content

PHP, HTML and Templating (Best approach?)


bachx

Recommended Posts

I currently use HTML strings within my PHP code to display output. And while it might not be best practice, I find it non-restrictive and I can easily add loops, manipulate variables, etc. within my display.

 

However in the interest of having a cleaner code I'm thinking of separating the HTML, without having to use a Template engine like Smarty.

 

I don't care much about replacement patterns to be honest, I don't mind some PHP code withing the HTML, however my biggest issue is loops and having to modify a variable within each loop. Say I have the following example code (Similar to what I'm using right now):

 


function student_output() {

    //Retrieve students from array
   $students_arr = students_info();

    $selected_student = $_GET['selected_student'];

    $output = '<div id="students_container">';
    $output .= '<div class="items_list">';

    $i = 1;

    //Loop through students
    foreach($students_arr as $key=>$value) {

if ($selected_student == $key) {
    $output .= '<div id="student_name_'.$i.'" class="selected">'.$value['student_name'].'</div>';
            $output .= '<div id="student_img_'.$i.'" class="selected"><img src="'.$value['student_image'].'" /></div>'; 
}
        else {
            $output .= '<div id="student_name_'.$i.'">'.$value['student_name'].'</div>';
        }

        $i++;

    }

    return $output;
    
}   

 

What's the best way to represent this in HTML cleanly without having too much PHP code within?

Link to comment
Share on other sites

That would be pretty much the way you have just done it. 

 

"Tidy" code isn't about striping the HTML from PHP (or vice versa), it's about making the code logical, ledgible (comments, tabulation, case consistancy etc.) and as modular as possible (modular may not be such a big thing these days, I dunno).  The only things you should be taking out of the pages are any lines that have no actual reason being there.

 

I have a good car analogy I can use if you need further convincing :D

Link to comment
Share on other sites

My issue was when the HTML code grows bigger and more complex, it's gonna be a bit of a mess having a wall of out-of-place HTML code in the middle of a PHP file. Thinking more about it though, the same mess is gonna be replicated but the other way around in an HTML file, unless there is a magical tidier way of doing it.

Link to comment
Share on other sites

Muddy_Funster, bachx is referring to separating the PHP (AKA "business") logic from the display logic. Obviously you will always need PHP to some degree within the HTML; after-all you have to use PHP to loop through a data set (excluding an XSLT approach). SMARTY templates are simply parsed and then 'compiled' into PHP-based templates.

 

A clean way to achieve this with standard PHP code is to include your template files that rely on a set bit of data.. For example:

 

PHP logic

$test_data = array('foo', 'bar');

include 'test_template.php';

 

PHP template

<table>
    <?php foreach ($test_data as $data) { ?>
        <tr>
            <td><?php echo $data; ?></td>
        </tr>
    <?php } ?>
</table>

 

Obviously this is very simple, but you can see how the PHP logic has been split from the display logic. With a better template structure and more planning, it would work well. In the end though this is all SMARTY templates boil down to, it's just coded through a more elegant (arguable) interface.

Link to comment
Share on other sites

MrAdam, while that works great for a basic display, my original question was on how to work with more complex ones. For example when you have to modify a variable, and maybe use an IF (or Switch) statement within each loop. So we're back to mixing logic and display again, defeating the whole purpose of separation.

 

Now I'm starting to think there is no optimal solution for this, in that case is there really any advantage of separating the HTML, knowing that there will be a considerable amount of PHP code in there?

Link to comment
Share on other sites

MrAdam, while that works great for a basic display, my original question was on how to work with more complex ones. For example when you have to modify a variable, and maybe use an IF (or Switch) statement within each loop. So we're back to mixing logic and display again, defeating the whole purpose of separation.

 

Ah but it's there where the fun part begins :) But this is easily solved using a FilterIterator for example. You could also adjust your logic and make sure you only pass what you also intend to show.

Link to comment
Share on other sites

So we're back to mixing logic and display again, defeating the whole purpose of separation.

 

No, not quite. Your templates files only contain display logic - simple control statements to get the output desired. As ignace was saying, your application code should do all the complex stuff and prepare the data so that you only require simple control statements within the display logic.

 

MrAdam, while that works great for a basic display, my original question was on how to work with more complex ones.

 

The code, as I mentioned, was purely just a simple example of how the logic is split. What you're asking is kind of like asking how to work with 'complex PHP' - do you have a more specific question?

Link to comment
Share on other sites

The code, as I mentioned, was purely just a simple example of how the logic is split. What you're asking is kind of like asking how to work with 'complex PHP' - do you have a more specific question?

 

Alright, here is something on top of my head. While not the most 'complex' code, I would like to know what's the optimal way to prepare/separate something similar in logic/display files:

 

function student_output() {

    //students_info() returns an array
    $students_arr = students_info();

    $output = '<div id="students_container">';
    $output .= '<div class="items_list">';

    $i = 1;

    //Loop through students
    foreach($students_arr as $key=>$value) {

        //Correct student names for specific cases, and assign to those ones special CSS classes
        switch($value['student_name']) {
	case 'Jim':
	   $student_name = 'James';
           $css_class = 'style_1';
	   break;

	case 'Mike':
                   $student_name = 'Michael';
	   $css_class = 'style_2';
	   break;

	default:
	   $student_name = $value['student_name'];
	   $css_class = 'default_style';
	   break;
}

        //Include student image also if the current key is similar to the 'selected_student' parameter
if ($_GET['selected_student'] == $key) {
    $output .= '<div id="student_name_'.$i.'" class="selected '.$css_class.'">'.$student_name.'</div>';
            $output .= '<div id="student_img_'.$i.'" class="selected"><img src="'.$value['student_image'].'" /></div>'; 
}
        else {
            $output .= '<div id="student_name_'.$i.'" class="'.$css_class.'">'.$student_name.'</div>';
        }

        $i++;
    }

    return $output; 
}   

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.